Fisher–Yates shuffle算法Go语言实现

来源:互联网 发布:rebacca minkoff知乎 编辑:程序博客网 时间:2024/05/18 21:38

The modern algorithm

/*-- To shuffle an array a of n elements (indices 0..n-1):for i from n−1 downto 1 doj ← random integer such that 0 ≤ j ≤ iexchange a[j] and a[i]*/func shuffle(items[] int)  {i := len(items) - 1for i >= 1 {j := rand.Int63n(int64(i + 1))items[i], items[j] = items[j], items[i]i--}}/*-- To shuffle an array a of n elements (indices 0..n-1):for i from 0 to n−2 do     j ← random integer such that i ≤ j < n     exchange a[i] and a[j] */func shuffle2(items[] int)  {i := 0n := len(items)for i <= n - 2 {j := rand.Int63n(int64(n - i)) + int64(i)items[i], items[j] = items[j], items[i]i++}}


0 0
原创粉丝点击