1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: alien.c-types kernel math namespaces sequences
4 io.backend io.binary combinators system vocabs.loader
5 summary math.bitwise byte-vectors fry byte-arrays ;
8 SYMBOL: system-random-generator
9 SYMBOL: secure-random-generator
10 SYMBOL: random-generator
12 GENERIC: seed-random ( tuple seed -- )
13 GENERIC: random-32* ( tuple -- r )
14 GENERIC: random-bytes* ( n tuple -- byte-array )
16 M: object random-bytes* ( n tuple -- byte-array )
17 [ [ <byte-vector> ] keep 4 /mod ] dip tuck
18 [ pick '[ _ random-32* 4 >le _ push-all ] times ]
21 [ 2drop ] [ random-32* 4 >le swap head over push-all ] if
24 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
26 ERROR: no-random-number-generator ;
28 M: no-random-number-generator summary
29 drop "Random number generator is not defined." ;
31 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
33 M: f random-32* ( obj -- * ) no-random-number-generator ;
35 : random-bytes ( n -- byte-array )
36 random-generator get random-bytes* ;
40 : random-integer ( n -- n' )
42 [ random-bytes >byte-array byte-array>bignum ]
43 [ 3 shift 2^ ] bi / * >integer ;
47 : random-bits ( n -- r ) 2^ random-integer ;
49 : random ( seq -- elt )
51 [ length random-integer ] keep nth
54 : randomize ( seq -- seq' )
55 dup length 1 (a,b] [ dup random pick exchange ] each ;
57 : delete-random ( seq -- elt )
58 [ length random-integer ] keep [ nth ] 2keep delete-nth ;
60 : with-random ( tuple quot -- )
61 random-generator swap with-variable ; inline
63 : with-system-random ( quot -- )
64 system-random-generator get swap with-random ; inline
66 : with-secure-random ( quot -- )
67 secure-random-generator get swap with-random ; inline
72 { [ os windows? ] [ "random.windows" require ] }
73 { [ os unix? ] [ "random.unix" require ] }
76 "random.mersenne-twister" require