2012-08-03 18:17:50 -04:00
|
|
|
! Copyright (c) 2012 Anonymous
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2015-07-19 15:36:07 -04:00
|
|
|
USING: arrays assocs combinators.random formatting fry kernel
|
|
|
|
macros math quotations sequences ;
|
2012-08-03 18:17:50 -04:00
|
|
|
IN: rosettacode.probabilistic-choice
|
|
|
|
|
|
|
|
! http://rosettacode.org/wiki/Probabilistic_choice
|
|
|
|
|
|
|
|
! Given a mapping between items and their required probability
|
|
|
|
! of occurrence, generate a million items randomly subject to the
|
|
|
|
! given probabilities and compare the target probability of
|
|
|
|
! occurrence versus the generated values.
|
|
|
|
|
|
|
|
! The total of all the probabilities should equal one. (Because
|
|
|
|
! floating point arithmetic is involved this is subject to
|
|
|
|
! rounding errors).
|
|
|
|
|
|
|
|
! Use the following mapping to test your programs:
|
|
|
|
! aleph 1/5.0
|
|
|
|
! beth 1/6.0
|
|
|
|
! gimel 1/7.0
|
|
|
|
! daleth 1/8.0
|
|
|
|
! he 1/9.0
|
|
|
|
! waw 1/10.0
|
|
|
|
! zayin 1/11.0
|
|
|
|
! heth 1759/27720 # adjusted so that probabilities add to 1
|
|
|
|
|
|
|
|
CONSTANT: data
|
|
|
|
{
|
|
|
|
{ "aleph" 1/5.0 }
|
|
|
|
{ "beth" 1/6.0 }
|
|
|
|
{ "gimel" 1/7.0 }
|
|
|
|
{ "daleth" 1/8.0 }
|
|
|
|
{ "he" 1/9.0 }
|
|
|
|
{ "waw" 1/10.0 }
|
|
|
|
{ "zayin" 1/11.0 }
|
|
|
|
{ "heth" f }
|
|
|
|
}
|
|
|
|
|
2015-07-19 14:42:46 -04:00
|
|
|
MACRO: case-probas ( data -- quot )
|
2015-07-19 15:36:07 -04:00
|
|
|
[ first2 [ 1quotation ] dip [ swap 2array ] when* ] map 1quotation ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
2015-07-19 15:36:07 -04:00
|
|
|
: expected ( data name -- float )
|
2016-07-11 22:50:37 -04:00
|
|
|
dupd of [ ] [ values sift sum 1 swap - ] ?if ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: generate ( # case-probas -- seq )
|
2015-07-19 15:36:07 -04:00
|
|
|
H{ } clone [
|
|
|
|
'[ _ casep _ inc-at ] times
|
|
|
|
] keep ; inline
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: normalize ( seq # -- seq )
|
2015-07-19 15:36:07 -04:00
|
|
|
[ clone ] dip '[ _ /f ] assoc-map ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: summarize1 ( name value data -- )
|
2015-07-19 15:36:07 -04:00
|
|
|
pick expected "%6s: %10f %10f\n" printf ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: summarize ( generated data -- )
|
|
|
|
"Key" "Value" "expected" "%6s %10s %10s\n" printf
|
2015-07-19 15:36:07 -04:00
|
|
|
'[ _ summarize1 ] assoc-each ;
|
2012-08-03 18:17:50 -04:00
|
|
|
|
|
|
|
: generate-normalized ( # proba -- seq )
|
|
|
|
[ generate ] [ drop normalize ] 2bi ; inline
|
|
|
|
|
|
|
|
: example ( # data -- )
|
|
|
|
[ case-probas generate-normalized ]
|
|
|
|
[ summarize ] bi ; inline
|