I recently needed to do the exact same thing
I found this code somewhere. ( I dont know where, I usually keep the URL )
so apologies if anyone is the uncredited author
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}
----- Original Message -----
From: "Chris McMahon" <[EMAIL PROTECTED]>
To: <[email protected]>
Sent: Monday, February 12, 2007 5:44 PM
Subject: [Wtr-general] OT: algorithm help?
> Hi...
>
> As usual, off topic. :)
>
> Say I have 3 methods a, b, c. Over the course of many iterations, I
> want to call each method a certain percentage of the time. Say I
> have a config file like
>
> method percentage
> a 30
> b 30
> c 40
>
> I'm thinking of writing code that will load up integer ranges like
> arange = [1..30]
> brange = [31..60]
> crange = [61..100]
>
> and then do
>
> many.times do |foo|
> num= rand(100)
> if num in arange
> a
> end
> if num in brange
> b
> end
> if num in crange
> end
>
> end #loop
>
>
> So two questons:
> First, is this is a sane approach? Is there any more elegant way to
> call an arbitrary method a certain percentage of the time for a random
> number of iterations?
>
> Second, if this is elegant enough, can you suggest a nice way to build
> the integer arrays nicely at runtime from the configuration
> information? The only algorithms I can think of turn out pretty ugly.
>
> Thanks...
> -Chris
> _______________________________________________
> Wtr-general mailing list
> [email protected]
> http://rubyforge.org/mailman/listinfo/wtr-general
>
_______________________________________________
Wtr-general mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/wtr-general