Skip to content

Instantly share code, notes, and snippets.

@cyberfox
Created January 27, 2012 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyberfox/1687900 to your computer and use it in GitHub Desktop.
Save cyberfox/1687900 to your computer and use it in GitHub Desktop.
Champagne Solution
if ARGV[0].nil?
puts "Usage:\n\truby #{__FILE__} {bad bottle#|test}"
exit
end
def guess_bottle(bad_bottle, silent=false)
waiters = []
(0..9).each do |waiter_number|
waiters[waiter_number] = []
(0..999).each do |bottle|
if (bottle & (2 ** waiter_number)) != 0
waiters[waiter_number] << bottle
end
end
end
puts "Who got sick from bottle #{bad_bottle}?" unless silent
sick_waiters = []
waiters.each_with_index do |waiter,index|
if waiter.include? bad_bottle
puts "Waiter #{index} got sick." unless silent
sick_waiters << index
end
end
sick_waiters.inject(0) { |accum, waiter| accum + (2 ** waiter) }
end
if ARGV[0] != 'test'
bad_bottle = ARGV[0].to_i
puts "Based on the waiters that got sick, the bad bottle is #{guess_bottle(bad_bottle)}"
else
(0..999).each do |bottle|
if bottle != guess_bottle(bottle, true)
puts "Failed on #{bottle}!"
exit
end
end
puts "No bottles failed!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment