GolangNote

Golang笔记

Golang 随机打乱数组/Slice

Permalink2

给定一个数组/列表/Slice,随机打乱顺序

Golang 随机打乱数组/Slice

Go: 随机打乱Slice顺序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    slice := []interface{}{"a", "b", "c", "d", "e", "f"}
    Shuffle(slice)
    fmt.Println(slice)
    for _, v := range slice {
        fmt.Println(v.(string))
    }
}

func Shuffle(slice []interface{}) {
    r := rand.New(rand.NewSource(time.Now().Unix()))
    for len(slice) > 0 {
        n := len(slice)
        randIndex := r.Intn(n)
        slice[n-1], slice[randIndex] = slice[randIndex], slice[n-1]
        slice = slice[:n-1]
    }
}

运行,每次输出都不同:

plaintext: 随机打乱Slice顺序结果输出
1
2
3
4
5
6
7
[f c e d b a]
f
c
e
d
b
a

Related articles

Golang telegram 机器人小试

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。...

Comments

There are 2 Comments to "Golang 随机打乱数组/Slice"

1 smallwhite says:
回复

为什么不用 rand.Shuffle ??

2 GolangNote says:
回复

@smallwhite 一点性能改善

Write a Comment to "Golang 随机打乱数组/Slice"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.3 Processed in 0ms