25
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sliceのシャッフル

Posted at
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]
	}
}

[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

25
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?