Skip to content

Instantly share code, notes, and snippets.

@k-hamada
Last active March 13, 2016 08:33
Show Gist options
  • Save k-hamada/ba27e070b729d60f936f to your computer and use it in GitHub Desktop.
Save k-hamada/ba27e070b729d60f936f to your computer and use it in GitHub Desktop.
module Lottery
class << self
def draw(probablity_rates, upper_limit = 10000)
chosen_value = rand(0...upper_limit)
probablity_rates.find_index{|probablity_rate|
chosen_value -= probablity_rate
chosen_value < 0
}
end
end
end
rates = [1000, 2000, 3000, 4000]
result = {}
10000.times do
index = Lottery.draw(rates, rates.inject(:+))
result[index] ||= 0
result[index] += 1
end
result.keys.sort.each do |k|
puts "#{k}, #{result[k]}"
end
__END__
0, 984
1, 1966
2, 3041
3, 4009
@k-hamada
Copy link
Author

Prelude> import Data.List
Prelude> let rates = [1000, 2000, 3000, 4000]
Prelude> let chosen_value = 2222
Prelude> findIndex (> chosen_value) $ scanl1 (+) rates
#=> Just 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment