2005-01-29 14:18:28 -05:00
|
|
|
! Copyright (C) 2003, 2005 Slava Pestov.
|
|
|
|
! See http://factor.sf.net/license.txt for BSD license.
|
|
|
|
IN: random USING: kernel lists math ;
|
2004-07-16 02:26:21 -04:00
|
|
|
|
2005-01-29 14:18:28 -05:00
|
|
|
: power-of-2? ( n -- ? ) dup dup neg bitand = ;
|
2004-11-25 21:51:47 -05:00
|
|
|
|
|
|
|
: (random-int-0) ( n bits val -- n )
|
2004-12-29 03:35:46 -05:00
|
|
|
3dup - + 1 < [
|
2004-11-25 21:51:47 -05:00
|
|
|
2drop (random-int) 2dup swap mod (random-int-0)
|
|
|
|
] [
|
2005-01-19 21:01:47 -05:00
|
|
|
2nip
|
2004-11-25 21:51:47 -05:00
|
|
|
] ifte ;
|
|
|
|
|
|
|
|
: random-int-0 ( max -- n )
|
2004-12-29 03:35:46 -05:00
|
|
|
1 + dup power-of-2? [
|
2004-11-25 21:51:47 -05:00
|
|
|
(random-int) * -31 shift
|
|
|
|
] [
|
|
|
|
(random-int) 2dup swap mod (random-int-0)
|
|
|
|
] ifte ;
|
|
|
|
|
2005-01-29 14:18:28 -05:00
|
|
|
: random-int ( min max -- n ) dupd swap - random-int-0 + ;
|
|
|
|
: random-boolean ( -- ? ) 0 1 random-int 0 = ;
|
|
|
|
: random-digit ( -- digit ) 0 9 random-int ;
|