> def calc(weights)
>    r = weights.inject(0){|s,x|s+x} * rand
>    weights.inject(0) {|s,x| s+=x; return x if s>=r;s}
>    weights[-1]
> end
> stat={}
> stat.default=0
> 1_000_000.times { stat[ calc([0.2, 0.5, 0.1, 0.3]) ] += 1 }
> stat.each {|k,v| printf "%4.2f %4.2f\n", k, v/1_000_000.0}

One major drawback for this is that it won't work out of the box for
values like calc([0.1,0.1,0.8])   That is, call def a 10% of the time,
def  b 10% of the time, def c 80% of the time.  It seems input values
have to be unique.

-C
_______________________________________________
Wtr-general mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/wtr-general

Reply via email to