Created
June 10, 2011 05:07
-
-
Save seven1m/1018262 to your computer and use it in GitHub Desktop.
Solution to PuzzleNode problem #4 - Robots vs. Lasers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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