factor/basis/random/random.factor

78 lines
2.0 KiB
Factor
Raw Normal View History

2008-03-19 17:18:03 -04:00
! Copyright (C) 2008 Doug Coleman.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
2008-03-19 17:18:03 -04:00
USING: alien.c-types kernel math namespaces sequences
2008-03-29 15:51:50 -04:00
io.backend io.binary combinators system vocabs.loader
2008-12-18 03:04:05 -05:00
summary math.bitwise byte-vectors fry byte-arrays
math.ranges ;
2007-09-20 18:09:08 -04:00
IN: random
SYMBOL: system-random-generator
2008-03-27 07:27:36 -04:00
SYMBOL: secure-random-generator
SYMBOL: random-generator
GENERIC: seed-random ( tuple seed -- )
GENERIC: random-32* ( tuple -- r )
2008-03-27 07:30:59 -04:00
GENERIC: random-bytes* ( n tuple -- byte-array )
2008-03-27 07:27:36 -04:00
M: object random-bytes* ( n tuple -- byte-array )
[ [ <byte-vector> ] keep 4 /mod ] dip tuck
[ pick '[ _ random-32* 4 >le _ push-all ] times ]
[
over zero?
[ 2drop ] [ random-32* 4 >le swap head over push-all ] if
] 2bi* ;
2008-03-27 07:27:36 -04:00
2008-03-29 00:20:33 -04:00
M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
2008-03-27 07:27:36 -04:00
ERROR: no-random-number-generator ;
2008-03-29 15:50:52 -04:00
M: no-random-number-generator summary
drop "Random number generator is not defined." ;
2008-03-27 07:27:36 -04:00
M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
M: f random-32* ( obj -- * ) no-random-number-generator ;
2008-03-27 07:30:59 -04:00
: random-bytes ( n -- byte-array )
random-generator get random-bytes* ;
2007-09-20 18:09:08 -04:00
<PRIVATE
: random-integer ( n -- n' )
dup log2 7 + 8 /i 1+
[ random-bytes >byte-array byte-array>bignum ]
[ 3 shift 2^ ] bi / * >integer ;
PRIVATE>
2008-10-05 23:08:13 -04:00
: random-bits ( n -- r ) 2^ random-integer ;
: random ( seq -- elt )
2008-09-06 20:13:59 -04:00
[ f ] [
[ length random-integer ] keep nth
2008-09-06 20:13:59 -04:00
] if-empty ;
2007-09-20 18:09:08 -04:00
2008-12-18 01:15:07 -05:00
: randomize ( seq -- seq' )
dup length 1 (a,b] [ dup random pick exchange ] each ;
: delete-random ( seq -- elt )
[ length random-integer ] keep [ nth ] 2keep delete-nth ;
2008-03-19 22:41:39 -04:00
2008-03-19 17:18:03 -04:00
: with-random ( tuple quot -- )
2008-03-19 22:41:39 -04:00
random-generator swap with-variable ; inline
2008-03-28 23:10:01 -04:00
: with-system-random ( quot -- )
system-random-generator get swap with-random ; inline
2008-03-28 23:10:01 -04:00
: with-secure-random ( quot -- )
secure-random-generator get swap with-random ; inline
USE: vocabs.loader
{
{ [ os windows? ] [ "random.windows" require ] }
{ [ os unix? ] [ "random.unix" require ] }
} cond
"random.mersenne-twister" require