factor/library/math/random.factor

22 lines
537 B
Factor
Raw Normal View History

! Copyright (C) 2003, 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: math USING: kernel ;
2004-07-16 02:26:21 -04:00
: power-of-2? ( n -- ? ) dup dup neg bitand = ;
2004-11-25 21:51:47 -05:00
: (random-int-0) ( n bits val -- n )
3dup - + 1 < [
2004-11-25 21:51:47 -05:00
2drop (random-int) 2dup swap mod (random-int-0)
] [
2nip
2004-11-25 21:51:47 -05:00
] ifte ;
: random-int-0 ( max -- n )
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 ;
: random-int ( min max -- n ) dupd swap - random-int-0 + ;