Skip to content

Commit 681f39f

Browse files
committed
Days 9 to 13 2022
1 parent 83f5591 commit 681f39f

20 files changed

+4669
-0
lines changed

2022/day-09/README.txt

+683
Large diffs are not rendered by default.

2022/day-09/day-09-input.txt

+2,000
Large diffs are not rendered by default.

2022/day-09/day-09-part-1.rb

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'set'
4+
5+
file_path = File.expand_path("../day-09-input.txt", __FILE__)
6+
input = File.read(file_path)
7+
8+
hx = hy = 0
9+
tx = ty = 0
10+
11+
visited = [[tx, ty]].to_set
12+
13+
input.each_line do |line|
14+
dir, v = line.split
15+
v = v.to_i
16+
17+
v.times do
18+
case dir
19+
when "R"
20+
hx += 1
21+
when "L"
22+
hx -= 1
23+
when "U"
24+
hy += 1
25+
when "D"
26+
hy -= 1
27+
end
28+
29+
# neighbour check
30+
next if (hx - tx).abs <= 1 && (hy - ty).abs <= 1
31+
32+
if hy != ty
33+
ty += (hy - ty).positive? ? 1 : -1
34+
end
35+
36+
if hx != tx
37+
tx += (hx - tx).positive? ? 1 : -1
38+
end
39+
40+
visited << [tx, ty]
41+
end
42+
end
43+
44+
puts visited.count

2022/day-09/day-09-part-2.rb

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'set'
4+
5+
file_path = File.expand_path("../day-09-input.txt", __FILE__)
6+
input = File.read(file_path)
7+
8+
# Head knot is at index 0
9+
knots = Array.new(10) { [0, 0] }
10+
11+
visited = [knots[-1].clone].to_set
12+
13+
input.each_line do |line|
14+
dir, v = line.split
15+
v = v.to_i
16+
17+
head = knots[0]
18+
v.times do
19+
case dir
20+
when "R"
21+
head[0] += 1
22+
when "L"
23+
head[0] -= 1
24+
when "U"
25+
head[1] += 1
26+
when "D"
27+
head[1] -= 1
28+
end
29+
30+
knots.each_cons(2) do |head, tail|
31+
# neighbour check
32+
next if (head[0] - tail[0]).abs <= 1 && (head[1] - tail[1]).abs <= 1
33+
34+
if head[1] != tail[1]
35+
tail[1] += (head[1] - tail[1]).positive? ? 1 : -1
36+
end
37+
38+
if head[0] != tail[0]
39+
tail[0] += (head[0] - tail[0]).positive? ? 1 : -1
40+
end
41+
end
42+
43+
visited << knots[-1].clone
44+
end
45+
end
46+
47+
puts visited.count

0 commit comments

Comments
 (0)