Posted at

sliceのシャッフル

More than 3 years have passed since last update.

package main

import (
"fmt"
"math/rand"
)

func main() {
n := 30
arr := generate(n)

fmt.Println(arr)
shuffle(arr)
fmt.Println(arr)
}

func generate(n int) []string {
arr := make([]string, n)
for i := range arr {
arr[i] = fmt.Sprintf("%02d", i)
}
return arr
}

func shuffle(data []string) {
n := len(data)
for i := n - 1; i >= 0; i-- {
j := rand.Intn(i + 1)
data[i], data[j] = data[j], data[i]
}
}

https://play.golang.org/p/He5P-cHZwk

[00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29]

[04 13 23 09 02 03 24 20 00 10 22 05 21 07 19 16 08 12 17 14 27 28 26 01 18 25 29 15 06 11]

Fisher–Yates shuffleというアルゴリズムだそうです。

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

(教えていただいた記録) https://twitter.com/sugyan/status/653922349931085826