前端之家收集整理的这篇文章主要介绍了
golang 面试题尝试解答,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
题目链接
交替打印数字和字母
package main
import (
"fmt"
)
func main() {
var IoUt,cout,done = make(chan bool),make(chan bool, 1),make(chan bool,1)
go func() {
iarr := []string{"1","2","3","4","5","6","7","8","9","10"}
for i := 0; i < len(iarr); i += 2 {
<-cout
fmt.Print(iarr[i])
fmt.Print(iarr[i+1])
IoUt <- true
}
}()
go func() {
carr := []string{"A","B","C","D","E","F","G","H","I","J"}
for i := 0; i < len(carr); i += 2 {
<-IoUt
fmt.Print(carr[i])
fmt.Print(carr[i+1])
fmt.Println("=========================")
cout <- true
}
done <- true
}()
cout <- true
<-done
}
权重抽奖
package main
import (
"math/rand"
"time"
"fmt"
)
var order_users map[string]int64 = map[string]int64{
"a": 10,"b": 6,"c": 3,"d": 12,"f": 19,}
func main() {
rand.NewSource(time.Now().Unix())
var maxx int64 = 0
var ans string = ""
for ans == "" {
for k,v := range order_users {
if e := int64(rand.Intn(20)); e < v {
if e > maxx {
maxx = e
ans = k
}
}
}
}
fmt.Println(ans)
}
题目链接
package main
import "fmt"
func print(start int,chs []chan int,finish chan int) {
now := start
res := make([]int, 0)
length := len(chs) - 1
for i := 0; i < 10; i++ {
<-chs[now]
res = append(res,now)
now = now + 1
if now > length {
now = now - length
}
chs[now] <- 1
}
fmt.Println(start,res)
finish <- 1
}
func main() {
chs := make([]chan int, 5)
for i := 0; i < len(chs); i++ {
chs[i] = make(chan int, 4)
chs[i] <- 1
}
finish := make(chan int, 4)
for i := 1; i < 5; i++ {
go print(i,chs,finish)
}
num := 0
for num != 4 {
select {
case <-finish:
num ++
}
}
}
原文链接:/go/187204.html