From 99122a8fb1bf352c739dbe6ed12f9e43a582405f Mon Sep 17 00:00:00 2001 From: Doug Coleman Date: Sat, 14 Feb 2009 14:25:48 -0600 Subject: [PATCH] use while to implement randomize (thanks joe!), document it --- basis/random/random-docs.factor | 9 +++++++++ basis/random/random-tests.factor | 6 ------ basis/random/random.factor | 10 ++++------ 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/basis/random/random-docs.factor b/basis/random/random-docs.factor index 01b389c19c..c7600a731f 100755 --- a/basis/random/random-docs.factor +++ b/basis/random/random-docs.factor @@ -57,6 +57,13 @@ HELP: with-system-random { with-random with-secure-random with-system-random } related-words +HELP: randomize +{ $values + { "seq" sequence } + { "seq" sequence } +} +{ $description "Randomizes a sequence in-place with the Fisher-Yates algorithm and returns the sequence." } ; + HELP: delete-random { $values { "seq" sequence } @@ -83,6 +90,8 @@ $nl { $subsection with-secure-random } "Implementation:" { $subsection "random-protocol" } +"Randomizing a sequence:" +{ $subsection randomize } "Deleting a random element from a sequence:" { $subsection delete-random } ; diff --git a/basis/random/random-tests.factor b/basis/random/random-tests.factor index 60cdee98ed..9607627b3d 100644 --- a/basis/random/random-tests.factor +++ b/basis/random/random-tests.factor @@ -18,14 +18,8 @@ IN: random.tests [ f ] [ 0 random ] unit-test -[ 0 ] [ { } >randomize-range length ] unit-test -[ 0 ] [ { 1 } >randomize-range length ] unit-test - [ { } ] [ { } randomize ] unit-test [ { 1 } ] [ { 1 } randomize ] unit-test [ f ] [ 100 [ { 0 1 } random ] replicate all-equal? ] unit-test - -[ t ] -[ { 1 2 } [ length ] [ >randomize-range length ] bi - 1 = ] unit-test diff --git a/basis/random/random.factor b/basis/random/random.factor index 9564e0a268..17bcc8f1b1 100755 --- a/basis/random/random.factor +++ b/basis/random/random.factor @@ -43,9 +43,6 @@ M: f random-32* ( obj -- * ) no-random-number-generator ; [ random-bytes >byte-array byte-array>bignum ] [ 3 shift 2^ ] bi / * >integer ; -: >randomize-range ( seq -- range/iota ) - length dup 2 < [ drop 0 iota ] [ 1+ 2 (a,b] ] if ; - PRIVATE> : random-bits ( n -- r ) 2^ random-integer ; @@ -55,9 +52,10 @@ PRIVATE> [ length random-integer ] keep nth ] if-empty ; -: randomize ( seq -- seq' ) - [ ] [ >randomize-range ] [ ] tri - '[ [ random ] [ 1- ] bi _ exchange ] each ; +: 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 ;