1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
include Math
Instruction = Struct.new(:direction, :blocks) do
def initialize(direction, blocks)
super(direction, blocks.to_i)
end
end
Turtle = Struct.new(:orientation, :location) do
def self.run(input)
instructions = parse(input)
turtles = [Turtle.new(-PI/2, [0,0])]
instructions.each.with_object(turtles) do |instruction, turtles|
turtles << turtles.last.turn(instruction.direction).step
(instruction.blocks - 1).times do
turtles << turtles.last.step
end
end
turtles
end
def self.parse(input)
input.split(', ').map {|step|
Instruction.new(*step.scan(/(?<turn>\w)(?<blocks>\d+)/)[0])
}
end
def turn(direction)
angle = case direction
when ?R
PI/2
when ?L
-PI/2
else
raise "unexpected direction: #{direction}"
end
Turtle.new(orientation + angle, location)
end
def step
x = location[0] + cos(orientation).to_i
y = location[1] + sin(orientation).to_i
Turtle.new(orientation, [x, y])
end
end
require 'minitest'
# require 'minitest/autorun'
class TestInstructions < Minitest::Test
def test_instructions
assert_distance 5, 'R2, L3'
assert_distance 2, 'R2, R2, R2'
assert_distance 12, 'R5, L5, R5, R3'
end
def assert_distance(expected, instructions)
assert_equal expected, Turtle.run(instructions).last.location.map(&:abs).inject(:+)
end
end
if __FILE__ == $0
turtles = Turtle.run(DATA.read)
p turtles.last
locations = turtles.map(&:location)
p locations.find {|location| locations.count(location) > 1 }
end
__END__