]> Cypherpunks repositories - gostls13.git/commitdiff
random permutation function
authorKen Thompson <ken@golang.org>
Sun, 16 Nov 2008 21:02:47 +0000 (13:02 -0800)
committerKen Thompson <ken@golang.org>
Sun, 16 Nov 2008 21:02:47 +0000 (13:02 -0800)
func perm(n int) *map[int]int

R=r
OCL=19340
CL=19340

src/lib/rand.go

index 8619cc48c2765034d4e1c5ff0ecaaa0aeb15c934..ef122d4a925ae0e3ab273870a25e303fac2513fb 100644 (file)
@@ -14,6 +14,7 @@ package       rand
 // urand32 - return random uint32
 // nrand, nrand31, nrand63 - return 0 <= random < n
 // frand, frand64, frand32 - return 0 <= random float, float64, float32 < 1
+// perm gives a random permutation map[int]int
 
 const
 (
@@ -162,6 +163,22 @@ frand() float
        return float(frand64())
 }
 
+export func
+perm(n int) *map[int]int
+{
+       m := new(map[int]int);
+       for i:=0; i<n; i++ {
+               m[i] = i;
+       }
+       for i:=0; i<n; i++ {
+               j := nrand(n);
+               t := m[i];
+               m[i] = m[j];
+               m[j] = t;
+       }
+       return m;
+}
+
 func
 init()
 {