Permalink
Browse files

added code to solve the puzzle

  • Loading branch information...
1 parent 1abd6a9 commit ba2f19227692d5bebcfae5d90e4faf7bb299429b @chopmo committed Mar 20, 2012
Showing with 36 additions and 0 deletions.
  1. +31 −0 04_robots_vs_lasers/lib/lasers.rb
  2. +5 −0 04_robots_vs_lasers/main
@@ -0,0 +1,31 @@
+module Lasers
+ module_function
+
+ def path(belt, direction)
+ north_line, robot_line, south_line = *belt.lines
+ robot_idx = robot_line.index("X")
+
+ # Create the forward paths from the viewpoint of the robot
+ north_path, south_path = \
+ if direction == :east
+ [north_line[robot_idx..-1],
+ south_line[robot_idx..-1]]
+ else
+ [north_line[0..robot_idx].reverse,
+ south_line[0..robot_idx].reverse]
+ end
+
+ # Combine to a single path of "active" positions
+ path_size = north_path.size
+ (0...path_size).map { |i| i.even? ? north_path[i] : south_path[i] }.join
+ end
+
+ def hits(p)
+ p.chars.select { |c| c == "|" }.size
+ end
+
+ def solve(input)
+ belts = input.split(/^\n/)
+ belts.map { |belt| hits(path(belt, :west)) <= hits(path(belt, :east)) ? "GO WEST" : "GO EAST" }
+ end
+end
View
@@ -0,0 +1,5 @@
+#!/usr/bin/env ruby -W
+$LOAD_PATH.unshift("lib")
+require 'lasers'
+
+puts Lasers::solve(open(ARGV[0]).read)

0 comments on commit ba2f192

Please sign in to comment.