Resolve day 2

main
Guillaume Dott 2021-12-02 11:02:03 +01:00
parent c7fa7b0567
commit b458fb9c99
2 changed files with 1057 additions and 0 deletions

1000
02/input 100644

File diff suppressed because it is too large Load Diff

57
02/script.rb 100755
View File

@ -0,0 +1,57 @@
#!/usr/bin/env ruby
require_relative '../common'
class Day02 < Day
def part1
input.each_with_object(Position.new) { |cmd, position| position.process cmd }.result
end
def part2
input.each_with_object(Position.new(use_aim: true)) { |cmd, position| position.process cmd }.result
end
class Position
def initialize(use_aim: false)
@use_aim = use_aim
@horizontal_position = 0
@depth = 0
@aim = 0
end
def process command
direction, value = command.match(/\A(forward|down|up) ([0-9]+)\z/).captures
send direction, value.to_i
end
def result
@horizontal_position * @depth
end
private
def forward value
@horizontal_position += value
@depth += @aim * value if @use_aim
end
def down value
if @use_aim
@aim += value
else
@depth += value
end
end
def up value
if @use_aim
@aim -= value
else
@depth -= value
end
end
end
end
Day02.run