Skip to content

Commit 79acca8

Browse files
committed
day 9 part b
1 parent 44435c4 commit 79acca8

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

09/a.rb

+2-5
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,8 @@
1010
dist.times do
1111
h = [h, dir].transpose.map(&:sum)
1212
xdiff, ydiff = h[0] - t[0], h[1] - t[1]
13-
14-
unless xdiff.abs < 2 && ydiff.abs < 2 # unless adjacent
15-
t = [t[0] + xdiff.clamp(-1, 1), t[1] + ydiff.clamp(-1, 1)]
16-
end
17-
13+
next if xdiff.abs < 2 && ydiff.abs < 2 # adjacent; do nothing
14+
t = [t[0] + xdiff.clamp(-1, 1), t[1] + ydiff.clamp(-1, 1)]
1815
visited << t
1916
end
2017
end

09/b.rb

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
require "set"
2+
3+
knots = Array.new(10, [0, 0])
4+
visited = Set.new([[0, 0]])
5+
dirs = { "U" => [0, 1], "D" => [0, -1], "R" => [1, 0], "L" => [-1, 0] }
6+
7+
File.foreach("09/input.txt", chomp: true) do |line|
8+
dir, dist = dirs[line[/[UDLR]/]], line[/\d+/].to_i
9+
10+
dist.times do
11+
knots.each_with_index do |knot, i|
12+
if i == 0
13+
knots[i] = [knot, dir].transpose.map(&:sum)
14+
else
15+
xdiff, ydiff = knots[i - 1][0] - knot[0], knots[i - 1][1] - knot[1]
16+
next if xdiff.abs < 2 && ydiff.abs < 2 # adjacent, do nothing
17+
knots[i] = [knot[0] + xdiff.clamp(-1, 1), knot[1] + ydiff.clamp(-1, 1)]
18+
end
19+
end
20+
21+
visited << knots.last
22+
end
23+
end
24+
25+
puts visited.count

0 commit comments

Comments
 (0)