make the random word actually return a number in the full range of the input and replace division words with bitwise ones

db4
Doug Coleman 2008-09-09 15:39:40 -05:00
parent c876388e6a
commit 7764242f66
3 changed files with 17 additions and 6 deletions

View File

@ -27,7 +27,13 @@ HELP: random
HELP: random-bytes HELP: random-bytes
{ $values { "n" "an integer" } { "byte-array" "a random integer" } } { $values { "n" "an integer" } { "byte-array" "a random integer" } }
{ $description "Outputs an integer with n bytes worth of bits." } ; { $description "Outputs an integer with n bytes worth of bits." }
{ $examples
{ $unchecked-example "USING: prettyprint random ;"
"5 random-bytes ."
"B{ 135 50 185 119 240 }"
}
} ;
HELP: random-bits HELP: random-bits
{ $values { "n" "an integer" } { "r" "a random integer" } } { $values { "n" "an integer" } { "r" "a random integer" } }

View File

@ -1,4 +1,4 @@
USING: random sequences tools.test kernel ; USING: random sequences tools.test kernel math math.functions ;
IN: random.tests IN: random.tests
[ 4 ] [ 4 random-bytes length ] unit-test [ 4 ] [ 4 random-bytes length ] unit-test
@ -9,3 +9,6 @@ IN: random.tests
[ 2 ] [ V{ 10 20 30 } [ delete-random drop ] keep length ] unit-test [ 2 ] [ V{ 10 20 30 } [ delete-random drop ] keep length ] unit-test
[ V{ } [ delete-random drop ] keep length ] must-fail [ V{ } [ delete-random drop ] keep length ] must-fail
[ t ] [ 10000 [ 0 [ drop 187 random + ] reduce ] keep / 2 * 187 10 ~ ] unit-test
[ t ] [ 10000 [ 0 [ drop 400 random + ] reduce ] keep / 2 * 400 10 ~ ] unit-test

View File

@ -2,7 +2,7 @@
! See http://factorcode.org/license.txt for BSD license. ! See http://factorcode.org/license.txt for BSD license.
USING: alien.c-types kernel math namespaces sequences USING: alien.c-types kernel math namespaces sequences
io.backend io.binary combinators system vocabs.loader io.backend io.binary combinators system vocabs.loader
summary ; summary math.bitwise ;
IN: random IN: random
SYMBOL: system-random-generator SYMBOL: system-random-generator
@ -29,15 +29,17 @@ M: f random-32* ( obj -- * ) no-random-number-generator ;
: random-bytes ( n -- byte-array ) : random-bytes ( n -- byte-array )
[ [
dup 4 rem zero? [ 1+ ] unless dup 3 mask zero? [ 1+ ] unless
random-generator get random-bytes* random-generator get random-bytes*
] keep head ; ] keep head ;
: random ( seq -- elt ) : random ( seq -- elt )
[ f ] [ [ f ] [
[ [
length dup log2 7 + 8 /i length [
random-bytes byte-array>bignum swap mod log2 8 + 8 /i
random-bytes byte-array>bignum
] keep wrap
] keep nth ] keep nth
] if-empty ; ] if-empty ;