|
1 | 1 | class Day14 |
| 2 | + KNOWN_TREE_PATTERN = [ |
| 3 | + ' # ', |
| 4 | + ' ### ', |
| 5 | + ' ##### ' |
| 6 | + ] |
2 | 7 | def part_one(input, w = 101, h = 103) |
3 | 8 | quadrants = [0, 0, 0, 0] |
4 | 9 | wd = w / 2 |
@@ -28,28 +33,54 @@ def part_two(input, w = 101, h = 103) |
28 | 33 | .map { |line| line.scan(/(-?\d+)/).flatten } |
29 | 34 | .map { |values| Robot.new(values[0].to_i, values[1].to_i, values[2].to_i, values[3].to_i, w, h) } |
30 | 35 |
|
31 | | - moves = 1 |
| 36 | + moves = 0 |
32 | 37 | loop do |
33 | | - bots.map(&:move!) |
34 | 38 | 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) |
35 | 43 |
|
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) |
40 | 47 | break |
41 | 48 | end |
42 | 49 |
|
| 50 | + bots.map(&:move!) |
43 | 51 | moves += 1 |
44 | 52 | end |
45 | 53 | end |
46 | 54 |
|
47 | | - def all_semetrical?(w, h, coords) |
| 55 | + def to_grid(w, h, coords) |
48 | 56 | grid = Array.new(h) { Array.new(w, '.') } |
49 | 57 | coords.each do |x, y| |
50 | 58 | grid[y][x] = '#' |
51 | 59 | 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) |
53 | 84 | end |
54 | 85 |
|
55 | 86 | def display_bots(w, h, coords) |
|
0 commit comments