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
9 SYMBOL: system-random-generator
10 SYMBOL: secure-random-generator
11 SYMBOL: random-generator
13 GENERIC: seed-random ( tuple seed -- )
14 GENERIC: random-32* ( tuple -- r )
15 GENERIC: random-bytes* ( n tuple -- byte-array )
17 M: object random-bytes* ( n tuple -- byte-array )
18 [ [ <byte-vector> ] keep 4 /mod ] dip tuck
19 [ pick '[ _ random-32* 4 >le _ push-all ] times ]
22 [ 2drop ] [ random-32* 4 >le swap head over push-all ] if
25 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
27 ERROR: no-random-number-generator ;
29 M: no-random-number-generator summary
30 drop "Random number generator is not defined." ;
32 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
34 M: f random-32* ( obj -- * ) no-random-number-generator ;
36 : random-bytes ( n -- byte-array )
37 random-generator get random-bytes* ;
41 : random-integer ( n -- n' )
43 [ random-bytes >byte-array byte-array>bignum ]
44 [ 3 shift 2^ ] bi / * >integer ;
48 : random-bits ( n -- r ) 2^ random-integer ;
50 : random ( seq -- elt )
52 [ length random-integer ] keep nth
55 : randomize ( seq -- seq' )
56 dup length 1 (a,b] [ dup random pick exchange ] each ;
58 : delete-random ( seq -- elt )
59 [ length random-integer ] keep [ nth ] 2keep delete-nth ;
61 : with-random ( tuple quot -- )
62 random-generator swap with-variable ; inline
64 : with-system-random ( quot -- )
65 system-random-generator get swap with-random ; inline
67 : with-secure-random ( quot -- )
68 secure-random-generator get swap with-random ; inline
73 { [ os windows? ] [ "random.windows" require ] }
74 { [ os unix? ] [ "random.unix" require ] }
77 "random.mersenne-twister" require