2022 Day 9 part 2
This commit is contained in:
parent
6b96700e2e
commit
400efd5802
1 changed files with 30 additions and 22 deletions
52
2022/day9.rb
52
2022/day9.rb
|
@ -4,36 +4,44 @@ def moveStep(dx, dy)
|
||||||
$headX += dx
|
$headX += dx
|
||||||
$headY += dy
|
$headY += dy
|
||||||
|
|
||||||
dx = $headX - $tailX
|
(curX, curY) = [$headX, $headY]
|
||||||
dy = $headY - $tailY
|
|
||||||
|
|
||||||
case [dx.abs, dy.abs]
|
$tail.each_index { |index|
|
||||||
when [0, 0], [1, 1], [1, 0], [0, 1] then
|
(tailX, tailY) = $tail[index]
|
||||||
|
|
||||||
when [2, 0], [0, 2], [2, 2] then
|
|
||||||
$tailX += dx <=> 0
|
|
||||||
$tailY += dy <=> 0
|
|
||||||
when [2, 1] then
|
|
||||||
$tailX += dx <=> 0
|
|
||||||
$tailY += dy <=> 0
|
|
||||||
when [1, 2] then
|
|
||||||
$tailX += dx <=> 0
|
|
||||||
$tailY += dy <=> 0
|
|
||||||
else
|
|
||||||
puts "Unknown: (#{dx}, #{dy})"
|
|
||||||
raise
|
|
||||||
end
|
|
||||||
|
|
||||||
$tailPositions.add [$tailX, $tailY]
|
dx = curX - tailX
|
||||||
|
dy = curY - tailY
|
||||||
|
|
||||||
|
case [dx.abs, dy.abs]
|
||||||
|
when [0, 0], [1, 1], [1, 0], [0, 1] then
|
||||||
|
# Stay the same
|
||||||
|
when [2, 0], [0, 2], [2, 2] then
|
||||||
|
tailX += dx <=> 0
|
||||||
|
tailY += dy <=> 0
|
||||||
|
when [2, 1] then
|
||||||
|
tailX += dx <=> 0
|
||||||
|
tailY += dy <=> 0
|
||||||
|
when [1, 2] then
|
||||||
|
tailX += dx <=> 0
|
||||||
|
tailY += dy <=> 0
|
||||||
|
else
|
||||||
|
puts "Unknown: (#{dx}, #{dy})"
|
||||||
|
raise
|
||||||
|
end
|
||||||
|
|
||||||
|
(curX, curY) = $tail[index] = [tailX, tailY]
|
||||||
|
}
|
||||||
|
|
||||||
|
$tailPositions.add [curX, curY]
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
def run count
|
def run count
|
||||||
$headX = 0
|
$headX = 0
|
||||||
$headY = 0
|
$headY = 0
|
||||||
$tailX = 0
|
|
||||||
$tailY = 0
|
|
||||||
|
|
||||||
|
$tail = [[$headX, $headY]] * (count - 1)
|
||||||
|
|
||||||
$tailPositions = Set[[$headX, $headY]]
|
$tailPositions = Set[[$headX, $headY]]
|
||||||
|
|
||||||
for line in File.readlines('day9.input')
|
for line in File.readlines('day9.input')
|
||||||
|
@ -60,5 +68,5 @@ def run count
|
||||||
end
|
end
|
||||||
|
|
||||||
puts "Part 1: #{run(2)}"
|
puts "Part 1: #{run(2)}"
|
||||||
|
puts "Part 2: #{run(10)}"
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue