2007-09-20 18:09:08 -04:00
|
|
|
|
2007-09-29 14:28:53 -04:00
|
|
|
USING: kernel namespaces arrays quotations sequences assocs combinators
|
2008-12-18 01:16:43 -05:00
|
|
|
mirrors math math.vectors random macros fry ;
|
2007-09-20 18:09:08 -04:00
|
|
|
|
|
|
|
IN: random-weighted
|
|
|
|
|
2008-01-12 17:23:34 -05:00
|
|
|
: probabilities ( weights -- probabilities ) dup sum v/n ;
|
2007-09-20 18:09:08 -04:00
|
|
|
|
|
|
|
: layers ( probabilities -- layers )
|
2008-04-26 03:01:43 -04:00
|
|
|
dup length 1+ [ head ] with map rest [ sum ] map ;
|
2007-09-20 18:09:08 -04:00
|
|
|
|
|
|
|
: random-weighted ( weights -- elt )
|
|
|
|
probabilities layers [ 1000 * ] map 1000 random [ > ] curry find drop ;
|
|
|
|
|
|
|
|
: random-weighted* ( seq -- elt )
|
2007-09-29 14:28:53 -04:00
|
|
|
dup [ second ] map swap [ first ] map random-weighted swap nth ;
|
|
|
|
|
|
|
|
MACRO: call-random-weighted ( exp -- )
|
2008-06-30 11:05:29 -04:00
|
|
|
[ keys ] [ values <enum> >alist ] bi
|
2008-12-18 01:16:43 -05:00
|
|
|
'[ _ random-weighted _ case ] ;
|