]> gitweb.factorcode.org Git - factor.git/blobdiff - basis/random/random.factor
Merge OneEyed's patch
[factor.git] / basis / random / random.factor
index a0b62cf7de59aecb0729e36fc6e1191cc4501a5f..ebde3802b458066c58ddd7e948fd7a9ec6346b95 100755 (executable)
@@ -2,7 +2,8 @@
 ! See http://factorcode.org/license.txt for BSD license.
 USING: alien.c-types kernel math namespaces sequences
 io.backend io.binary combinators system vocabs.loader
-summary math.bitwise ;
+summary math.bitwise byte-vectors fry byte-arrays
+math.ranges ;
 IN: random
 
 SYMBOL: system-random-generator
@@ -14,7 +15,12 @@ GENERIC: random-32* ( tuple -- r )
 GENERIC: random-bytes* ( n tuple -- byte-array )
 
 M: object random-bytes* ( n tuple -- byte-array )
-    [ random-32* ] curry replicate [ 4 >le ] map concat ;
+    [ [ <byte-vector> ] keep 4 /mod ] dip
+    [ pick '[ _ random-32* 4 >le _ push-all ] times ]
+    [
+        over zero?
+        [ 2drop ] [ random-32* 4 >le swap head over push-all ] if
+    ] bi-curry bi* ;
 
 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
 
@@ -28,16 +34,13 @@ M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
 M: f random-32* ( obj -- * ) no-random-number-generator ;
 
 : random-bytes ( n -- byte-array )
-    [
-        dup 3 mask zero? [ 1+ ] unless
-        random-generator get random-bytes*
-    ] keep head ;
+    random-generator get random-bytes* ;
 
 <PRIVATE
 
 : random-integer ( n -- n' )
     dup log2 7 + 8 /i 1+
-    [ random-bytes byte-array>bignum ]
+    [ random-bytes >byte-array byte-array>bignum ]
     [ 3 shift 2^ ] bi / * >integer ;
 
 PRIVATE>
@@ -49,6 +52,11 @@ PRIVATE>
         [ length random-integer ] keep nth
     ] if-empty ;
 
+: randomize ( seq -- seq )
+    dup length [ dup 1 > ]
+    [ [ random ] [ 1- ] bi [ pick exchange ] keep ]
+    while drop ;
+
 : delete-random ( seq -- elt )
     [ length random-integer ] keep [ nth ] 2keep delete-nth ;