1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays assocs combinators.random formatting kernel
4 math quotations sequences ;
5 IN: rosettacode.probabilistic-choice
7 ! http://rosettacode.org/wiki/Probabilistic_choice
9 ! Given a mapping between items and their required probability
10 ! of occurrence, generate a million items randomly subject to the
11 ! given probabilities and compare the target probability of
12 ! occurrence versus the generated values.
14 ! The total of all the probabilities should equal one. (Because
15 ! floating point arithmetic is involved this is subject to
18 ! Use the following mapping to test your programs:
26 ! heth 1759/27720 # adjusted so that probabilities add to 1
40 MACRO: case-probas ( data -- quot )
41 [ first2 [ 1quotation ] dip [ swap 2array ] when* ] map 1quotation ;
43 : expected ( data name -- float )
44 dupd of [ ] [ values sift sum 1 swap - ] ?if ;
46 : generate ( # case-probas -- seq )
48 '[ _ casep _ inc-at ] times
51 : normalize ( seq # -- seq )
52 [ clone ] dip '[ _ /f ] assoc-map ;
54 : summarize1 ( name value data -- )
55 pick expected "%6s: %10f %10f\n" printf ;
57 : summarize ( generated data -- )
58 "Key" "Value" "expected" "%6s %10s %10s\n" printf
59 '[ _ summarize1 ] assoc-each ;
61 : generate-normalized ( # proba -- seq )
62 [ generate ] [ drop normalize ] 2bi ; inline
64 : example ( # data -- )
65 [ case-probas generate-normalized ]
66 [ summarize ] bi ; inline