Skip to content

Instantly share code, notes, and snippets.

@seven1m
Created June 10, 2011 05:07
Show Gist options
  • Select an option

  • Save seven1m/1018262 to your computer and use it in GitHub Desktop.

Select an option

Save seven1m/1018262 to your computer and use it in GitHub Desktop.
Solution to PuzzleNode problem #4 - Robots vs. Lasers
#!/usr/bin/env ruby
class Enumerator
def count_with_index
count = 0
each_with_index do |item, index|
count += yield(item, index) ? 1 : 0
end
count
end
end
class Robot
def initialize(text)
@north, @conveyor, @south = text.split(/\n/)
end
def run
pos = @conveyor.index('X')
east_hits = @north[pos..-1].chars.count_with_index { |p, i| i.even? && p == '|' } +
@south[pos..-1].chars.count_with_index { |p, i| i.odd? && p == '|' }
west_hits = @north[0..pos].reverse.chars.count_with_index { |p, i| i.even? && p == '|' } +
@south[0..pos].reverse.chars.count_with_index { |p, i| i.odd? && p == '|' }
east_hits < west_hits ? 'GO EAST' : 'GO WEST'
end
end
if $0 == __FILE__
ARGF.read.split(/\n\n/).each do |robot|
puts Robot.new(robot).run
end
end
require 'test/unit'
require './robot'
class OutputTest < Test::Unit::TestCase
def test_west
assert_equal 'GO WEST', Robot.new("#|#|#|##\n---X----\n###||###").run
end
def test_east
assert_equal 'GO EAST', Robot.new("##|#|#|#\n----X---\n###||###").run
end
def test_tie
assert_equal 'GO WEST', Robot.new("##|#|#|#\n----X---\n###|||##").run
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment