Skip to content

Instantly share code, notes, and snippets.

@leobessa
Created May 31, 2011 19:33
Show Gist options
  • Save leobessa/1001115 to your computer and use it in GitHub Desktop.
Save leobessa/1001115 to your computer and use it in GitHub Desktop.
require 'fiber'
class Bot
def initialize(color)
@position = 1
@color = color
@fiber = Fiber.new do |buttons|
while next_button = buttons.find{ |c,p| c == @color }
if buttons.first == [@color,@position] && !$pushed
push_button(@position)
remaining_buttons = buttons.drop(1)
$pushed = true
break if remaining_buttons.empty?
buttons = Fiber.yield(remaining_buttons)
else
next_position = next_button[1]
move_to_button(next_position)
buttons = Fiber.yield(buttons)
end
end
buttons
end
end
def resume(buttons)
@fiber.resume(buttons)
end
def push_button(number)
#puts "#{@color}@#{@position} - Push button #{number}"
end
def move_to_button(target)
old_postion = @position
message = (target <=> @position) == 0 ? "Stay at" : "Move to"
@position = @position + (target <=> @position)
#puts "#{@color}@#{old_postion} - #{message} button #{@position}"
end
def alive?
@fiber.alive?
end
end
ARGF.readlines.drop(1).each_with_index do |line,index|
buttons = line[2..-1].scan(/(\w) (\d+)/).map{ |color,position| [color,position.to_i]}
#puts "buttons: #{buttons}"
orange = Bot.new('O')
blue = Bot.new('B')
bots = [orange,blue]
time = 0
while bots.any?(&:alive?)
$pushed = false
time = time + 1
buttons = bots.select(&:alive?).inject(buttons) do |buttons,bot|
bot.resume(buttons)
end
end
puts("Case #%d: %d" % [index+1, time] )
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment