# golang 数组 slice 乱序

csapr1987 · · 10037 次点击 · · 开始浏览

``````package main

import "fmt"
import "math/rand"
import "time"

var (
rr = rand.New(rand.NewSource(time.Now().UnixNano()))
a1 = [2]int{}
a2 = [10]int{}
)

func main() {
a := []int{0, 1}
for i := 0; i < 10000; i++ {
randslice()
//fmt.Println(rr.Intn(10))
sliceOutOfOrder(a)
}
fmt.Println(a1)
fmt.Println(a2)
}
func sliceOutOfOrder(in []int) []int {
l := len(in)
for i := l - 1; i > 0; i-- {
r := rr.Intn(i)
in[r], in[i] = in[i], in[r]
}
a1[in[0]] += 1
return in
}

func randslice() {
in := rr.Perm(10)
a2[in[0]] += 1
}
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

``````package main

import "fmt"
import "math/rand"
import "time"

var (
rr = rand.New(rand.NewSource(time.Now().UnixNano()))
a1 = [2]int{}
a2 = [10]int{}
)

func main() {
a := []int{0, 1}
for i := 0; i < 10000; i++ {
randslice()
//fmt.Println(rr.Intn(10))
sliceOutOfOrder(a)
}
fmt.Println(a1)
fmt.Println(a2)
}
func sliceOutOfOrder(in []int) []int {
l := len(in)
for i := l - 1; i > 0; i-- {
r := rr.Intn(i)
in[r], in[i] = in[i], in[r]
}
a1[in[0]] += 1
return in
}

func randslice() {
in := rr.Perm(10)
a2[in[0]] += 1
}
``````