]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/math/rand/v2/rand.go
math/rand/v2: simplify Perm
[gostls13.git] / src / math / rand / v2 / rand.go
index 7e8be1ac4f23b20ffb21efbe21813028973db48d..c6030f77fc8b5e998d94681495dc77c5246ffd9f 100644 (file)
@@ -230,18 +230,12 @@ func (r *Rand) Float32() float32 {
 // Perm returns, as a slice of n ints, a pseudo-random permutation of the integers
 // in the half-open interval [0,n).
 func (r *Rand) Perm(n int) []int {
-       m := make([]int, n)
-       // In the following loop, the iteration when i=0 always swaps m[0] with m[0].
-       // A change to remove this useless iteration is to assign 1 to i in the init
-       // statement. But Perm also effects r. Making this change will affect
-       // the final state of r. So this change can't be made for compatibility
-       // reasons for Go 1.
-       for i := 0; i < n; i++ {
-               j := r.IntN(i + 1)
-               m[i] = m[j]
-               m[j] = i
+       p := make([]int, n)
+       for i := range p {
+               p[i] = i
        }
-       return m
+       r.Shuffle(len(p), func(i, j int) { p[i], p[j] = p[j], p[i] })
+       return p
 }
 
 // Shuffle pseudo-randomizes the order of elements.