factor/extra/random-weighted/random-weighted.factor

21 lines
631 B
Factor
Raw Normal View History

2007-09-20 18:09:08 -04:00
USING: kernel namespaces arrays quotations sequences assocs combinators
2008-03-29 00:00:20 -04:00
mirrors math math.vectors random macros bake ;
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-01-09 17:36:30 -05:00
dup length 1+ [ head ] with map 1 tail [ 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 )
dup [ second ] map swap [ first ] map random-weighted swap nth ;
MACRO: call-random-weighted ( exp -- )
[ keys ] [ values <enum> >alist ] bi swap
[ , random-weighted , case ] bake ;