Skip to content

Instantly share code, notes, and snippets.

@jcamenisch
Created June 10, 2011 15:44
Show Gist options
  • Save jcamenisch/1019098 to your computer and use it in GitHub Desktop.
Save jcamenisch/1019098 to your computer and use it in GitHub Desktop.
Solution to Puzzle Node's puzzle #4

Robots vs. Lasers

Solution to Puzzle Node's puzzle #4. Execute with

cat input.txt | ruby process.rb > output.txt
class Wall
attr_reader :text
def initialize(text)
@text = text
@lasers = []
@text.each_char do |c|
@lasers << (c == '|' ? 1 : 0)
end
end
def hits (position, direction, polarity)
lasers = direction == :west ?
@lasers[0..position].reverse :
@lasers[position..-1]
lasers = lasers.values_at(* lasers.each_index.select {|e| e.even? ^ (polarity == :odd)}).reduce(0, :+)
end
end
STDIN.read.split("\n\n").each do |problem|
lines = problem.split("\n")
north_wall = Wall.new(lines[0])
south_wall = Wall.new(lines[2])
position = lines[1].index('X')
if north_wall.hits(position, :west, :even) + south_wall.hits(position, :west, :odd) >
north_wall.hits(position, :east, :even) + south_wall.hits(position, :east, :odd) then
puts 'GO EAST'
else
puts 'GO WEST'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment