-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday02.rb
44 lines (36 loc) · 1.06 KB
/
day02.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
# frozen_string_literal: true
course_readings = File.readlines('../inputs/2021/day02-input-01.txt').map do |line|
split_line = line.split
[split_line[0], split_line[1].to_i]
end
##########
# PART 1 #
##########
def sum_commands(command, input_array)
input_array.reduce(0) do |accumulation, command_value|
accumulation + (command_value[0] == command ? command_value[1] : 0)
end
end
forward = sum_commands('../inputs/2021/forward', course_readings)
down = sum_commands('../inputs/2021/down', course_readings)
up = sum_commands('../inputs/2021/up', course_readings)
depth = down - up
puts "Our new position is #{forward} forward at #{depth} depth, which multiply to give #{forward * depth}"
##########
# PART 2 #
##########
aim = 0
depth = 0
horizontal_position = 0
course_readings.each do |command, value|
case command
when 'forward'
horizontal_position += value
depth += aim * value
when 'up'
aim -= value
when 'down'
aim += value
end
end
puts "Our new position is (#{depth}, #{horizontal_position}) i.e. #{depth * horizontal_position}"