Refactoring

This commit is contained in:
Sven Weidauer 2022-12-10 17:04:33 +01:00
parent 6c3937e4f8
commit 6b96700e2e

View file

@ -1,12 +1,5 @@
require "set" require "set"
$headX = 0
$headY = 0
$tailX = 0
$tailY = 0
$tailPositions = Set[[$tailX, $tailY]]
def moveStep(dx, dy) def moveStep(dx, dy)
$headX += dx $headX += dx
$headY += dy $headY += dy
@ -35,28 +28,37 @@ def moveStep(dx, dy)
end end
for line in File.readlines('day9.input') def run count
unless /^(?<dir>[RLUD]) (?<steps>\d+)$/ =~ line $headX = 0
puts "Failed to parse #{line}" $headY = 0
raise $tailX = 0
$tailY = 0
$tailPositions = Set[[$headX, $headY]]
for line in File.readlines('day9.input')
unless /^(?<dir>[RLUD]) (?<steps>\d+)$/ =~ line
puts "Failed to parse #{line}"
raise
end
steps = steps.to_i
case dir
when "R" then
steps.times { moveStep 1, 0 }
when "L" then
steps.times { moveStep -1, 0 }
when "U" then
steps.times { moveStep 0, 1 }
when "D" then
steps.times { moveStep 0, -1 }
end
end end
steps = steps.to_i $tailPositions.count
case dir
when "R" then
steps.times { moveStep 1, 0 }
when "L" then
steps.times { moveStep -1, 0 }
when "U" then
steps.times { moveStep 0, 1 }
when "D" then
steps.times { moveStep 0, -1 }
else
raise
end
end end
puts $tailPositions.count puts "Part 1: #{run(2)}"