Last active
September 4, 2018 23:50
-
-
Save whalesalad/d3d61aca3c1ae13b11703bfe8324a879 to your computer and use it in GitHub Desktop.
Given real usage statistics, build probabilities around choices and give me a random item
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StochasticHash | |
attr_accessor :data | |
def initialize(data) | |
@data = data | |
end | |
def total | |
@total ||= data.values.sum | |
end | |
def build_ranges | |
baseline = 0 | |
ret = {} | |
data.each do |key, value| | |
ret[(baseline..baseline+value)] = key | |
baseline += value | |
end | |
return ret | |
end | |
def ranges | |
@ranges ||= build_ranges | |
end | |
def pick | |
number = rand(total) | |
ranges.each do |range, solution| | |
if range.include?(number) | |
return solution | |
end | |
end | |
# Fall back to just picking something | |
return data.keys.sample | |
end | |
end | |
# USAGE | |
quality_choices = StochasticHash.new({ | |
prime: 1_272_838, | |
choice: 15_582_961, | |
select: 3_925_873, | |
standard: 596, | |
commercial: 4_148, | |
utility: 24_878, | |
cutter: 0, | |
cannery: 0 | |
}) | |
quality_choices.pick | |
=> :choice |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment