Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Last active August 29, 2015 14:01
Show Gist options
  • Save tkfm-yamaguchi/4391b7c22ab58041729f to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/4391b7c22ab58041729f to your computer and use it in GitHub Desktop.
###
# 16.
# You have eight balls all of the same size. 7 of them weigh the same, and one of them weighs slightly more.
# How can you find the ball that is heavier by using a balance and only two weighings?
###
module Generator
def self.generate_heavier_index(max=8)
Time.now.sec.modulo(max)
end
end
class Ball
attr_accessor :index
def initialize(index, is_heavy)
@index = index
@is_heavy = index == is_heavy
end
def heavy?
@is_heavy
end
end
class Balance
MAX_WEIGHING_TIME = 2
def initialize
@count = 0
end
def weighing(left, right)
count_up!
_left = Array(left)
_right = Array(right)
case
when !_left.find(&:heavy?).nil?
1
when !_right.find(&:heavy?).nil?
-1
else
0
end
end
def heavier?(left, right)
count_up!
return left unless Array(left).find(&:heavy?).nil?
return right unless Array(right).find(&:heavy?).nil?
nil
end
def count_up!
raise "You have already been weighing 2 times" if @count > MAX_WEIGHING_TIME
@count += 1
end
end
heavier_index = Generator.generate_heavier_index
balls = 8.times.map{|i| Ball.new(i, heavier_index) }
_balls = balls.dup
balance = Balance.new
heaviers = balance.heavier?(balls.pop(3), balls.pop(3)) || balls
heavy_one = balance.heavier?(heaviers.pop, heaviers.pop) || heaviers.pop
puts <<EOM
Concluded: heavy ball's index maybe #{ heavy_one.index }.
Actually : heavy ball's index is #{ heavier_index }.
EOM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment