Skip to content

Instantly share code, notes, and snippets.

@JoshMcKin
Created May 19, 2011 19:43
Show Gist options
  • Save JoshMcKin/981561 to your computer and use it in GitHub Desktop.
Save JoshMcKin/981561 to your computer and use it in GitHub Desktop.
Guess the number of each of the supplied values necessary to get the desired total
def self.guessing_game(values=[2.5,10.95,55.25],multi_sum=4,total_goal=79.65)
results = nil
total_amount = 0.0
length = values.length
((multi_sum ** length) / (multi_sum)).times do |i|
total = 0
possible = []
total_amount = 0.0.to_d # use decimal for accuracy
length.times do |b|
if total == multi_sum
new_number = 1
elsif b == (length - 1)
new_number = (multi_sum) - total
else
last = (multi_sum) - total
last = 1 if last < 1
new_number = Random.new.rand(0..(last - 1))
new_number = 1 if new_number == 0
end
possible << new_number
total += new_number
total_amount += (values[b] * new_number.to_d)# use decimal for accuracy
end
puts "#{possible}"
if total_amount == total_goal
guessed = []
values.each_with_index do |occurr,i|
possible[i].times do
guessed << occurr
end
end
results = guessed
break
end
end
results
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment