martinus
1/27/2005 4:40:00 PM
> BTW, I'd be interested if anyone found a nicer looking solution to
> do a weighted rand.
What you are doing is called Roulett wheel selection, which is often
used as a selection algorithm when using genetic algorithms. I think
this is a bit nicer:
def choose
# sum up all values
sum = @biases.values.inject(0) {|sum, val| sum + val }
# choose something
search_sum = rand(sum)
# count up until found
current_sum = 0
found = @biases.detect do |key, value|
current_sum += value
current_sum > search_sum
end
found[0]
end
martinus