-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12.rb
57 lines (53 loc) · 1.41 KB
/
day12.rb
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
input = File.read("day12_input.txt").lines.map do |l|
{ dir: l[0], dist: l[1..-1].to_i }
end
directions = ['N', 'E', 'S', 'W']
# Part 1
ship = { x: 0, y: 0, dir: 1 }
input.each do |inst|
dir = inst[:dir] == 'F' ? directions[ship[:dir]] : inst[:dir]
case dir
when 'N'
ship[:y] += inst[:dist]
when 'E'
ship[:x] += inst[:dist]
when 'S'
ship[:y] -= inst[:dist]
when 'W'
ship[:x] -= inst[:dist]
when 'L'
ship[:dir] = (ship[:dir] - (inst[:dist] / 90)) % 4
when 'R'
ship[:dir] = (ship[:dir] + (inst[:dist] / 90)) % 4
end
end
p ship[:x].abs + ship[:y].abs
# Part 2
waypoint = { x: 10, y: 1 }
ship = { x: 0, y: 0 }
input.each do |inst|
case inst[:dir]
when 'N'
waypoint[:y] += inst[:dist]
when 'E'
waypoint[:x] += inst[:dist]
when 'S'
waypoint[:y] -= inst[:dist]
when 'W'
waypoint[:x] -= inst[:dist]
when 'L', 'R'
deg = inst[:dir] == 'L' ? -inst[:dist] : inst[:dist]
case deg % 360
when 90
waypoint[:y],waypoint[:x] = -waypoint[:x],waypoint[:y]
when 180
waypoint[:x],waypoint[:y] = -waypoint[:x],-waypoint[:y]
when 270
waypoint[:y],waypoint[:x] = waypoint[:x],-waypoint[:y]
end
when 'F'
ship[:x] += waypoint[:x]*inst[:dist]
ship[:y] += waypoint[:y]*inst[:dist]
end
end
p ship[:x].abs + ship[:y].abs