m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/12/b.rb
blob: 4bd8ed062954d5ca06486789b2bd3fcfea088cc5 (plain)
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
instructions = File.readlines('input.txt').map do |line|
  [line.slice(0, 1), line.slice(1, line.length).to_i]
end

def rotate n, e, direction
  case direction
  when 0
    [n, e]
  when 90
    [e, -n]
  when 180
    [-n, -e]
  when 270
    [-e, n]
  end
end

ship_n = 0
ship_e = 0
waypoint_n = 1
waypoint_e = 10

instructions.each do |instruction|
  case instruction[0]
  when 'N'
    waypoint_n += instruction[1]
  when 'S'
    waypoint_n -= instruction[1]
  when 'E'
    waypoint_e += instruction[1]
  when 'W'
    waypoint_e  -= instruction[1]
  when 'F'
    ship_n += waypoint_n * instruction[1]
    ship_e += waypoint_e * instruction[1]
  when 'L'
    waypoint_n, waypoint_e = rotate waypoint_n, waypoint_e, instruction[1]
  when 'R'
    waypoint_n, waypoint_e = rotate waypoint_n, waypoint_e, (-instruction[1] % 360)
  end
end

puts ship_n.abs + ship_e.abs