go语言中实现数组随机输出打印示例代码
go随机打乱列表数组,可以通过rand.Perm()函数完成
代码示例:对列表数组进行洗牌
1.随机洗牌函数编写
\models\helpers.go
//公共函数
package models
import (
"fmt"
"math/rand"
"time"
)
//对列表数组进行随机/洗牌
func ShuffleList(start, end int) []int {
if end < start {
start, end = end, start
}
length := end - start
rand.Seed(time.Now().UTC().UnixNano())
list := rand.Perm(length)
for index, _ := range list {
list[index] += start
}
return list
}
2.控制器调用测试
package controllers
import (
"fmt"
"gblog/models"
)
// TestController is a test control
type TestController struct {
//beego.Controller
BaseController
}
func (c *TestController) Aaa() {
mapList := make([]map[int]int, 4)
mapList[0] = map[int]int{1: 1}
mapList[1] = map[int]int{2: 2}
mapList[2] = map[int]int{3: 3}
mapList[3] = map[int]int{4: 4}
//随机洗牌
shuffled := models.ShuffleList(0, len(mapList))
fmt.Printf("map数据 : %v\n", mapList)
fmt.Printf("洗牌后的map数据 : %v\n", shuffled)
}
效果:
相关文章