Skip to content

Commit f945b3c

Browse files
committed
Day 14 - Puzzle 2 - Attempt 2
Try to detect the top
1 parent ba776fe commit f945b3c

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

lib/solutions/day_14.rb

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
class Day14
2+
KNOWN_TREE_PATTERN = [
3+
' # ',
4+
' ### ',
5+
' ##### '
6+
]
27
def part_one(input, w = 101, h = 103)
38
quadrants = [0, 0, 0, 0]
49
wd = w / 2
@@ -28,28 +33,54 @@ def part_two(input, w = 101, h = 103)
2833
.map { |line| line.scan(/(-?\d+)/).flatten }
2934
.map { |values| Robot.new(values[0].to_i, values[1].to_i, values[2].to_i, values[3].to_i, w, h) }
3035

31-
moves = 1
36+
moves = 0
3237
loop do
33-
bots.map(&:move!)
3438
coords = bots.map(&:p)
39+
grid = to_grid(w, h, coords)
40+
bounding_box = bounding_box(coords)
41+
42+
pattern = extract_pattern(grid, bounding_box)
3543

36-
if all_semetrical?(w, h, coords)
37-
puts "--- Move #{moves} ---"
38-
display_bots(w, h, bots.map(&:p))
39-
puts ''
44+
if matches_christmas_tree?(pattern)
45+
puts "Found it after #{moves} moves"
46+
display_bots(w, h, coords)
4047
break
4148
end
4249

50+
bots.map(&:move!)
4351
moves += 1
4452
end
4553
end
4654

47-
def all_semetrical?(w, h, coords)
55+
def to_grid(w, h, coords)
4856
grid = Array.new(h) { Array.new(w, '.') }
4957
coords.each do |x, y|
5058
grid[y][x] = '#'
5159
end
52-
grid.all? { |row| row == row.reverse }
60+
grid
61+
end
62+
63+
def bounding_box(coords)
64+
x_values = coords.map { |x, _| x }
65+
y_values = coords.map { |_, y| y }
66+
67+
[x_values.min, y_values.min, x_values.max, y_values.max]
68+
end
69+
70+
def extract_pattern(grid, bounding_box)
71+
x_min, y_min, x_max, y_max = bounding_box
72+
pattern = []
73+
(y_min..y_max).each do |y|
74+
row = grid[y][x_min..x_max].join
75+
pattern << row
76+
end
77+
pattern
78+
end
79+
80+
def matches_christmas_tree?(pattern)
81+
pattern[0].count('#') == 1 &&
82+
(pattern[1].count('#') == 2 || pattern[1].count('#') == 3) &&
83+
(pattern[1].count('#') == 2 || pattern[1].count('#') == 5)
5384
end
5485

5586
def display_bots(w, h, coords)

0 commit comments

Comments
 (0)