|
1 | | -DIRS = [ [0,-1], [1,0], [0,1], [-1,0] ] |
| 1 | +DIRS = [[0,-1], [1,0], [0,1], [-1,0]] |
2 | 2 |
|
3 | | -def in_bounds(grid, x, y) = y >= 0 && y < grid.length && x >= 0 && x < grid[y].length |
| 3 | +def in_bounds(grid, x, y) = |
| 4 | + y >= 0 && |
| 5 | + y < grid.length && |
| 6 | + x >= 0 && |
| 7 | + x < grid[y].length |
4 | 8 |
|
5 | | -def find_trails(grid, v, x, y) |
| 9 | +def find_trails(grid, x, y, v=0, steps=[[x,y]]) |
6 | 10 | return [] unless in_bounds(grid, x, y) && grid[y][x] == v |
7 | | - return [[x,y]] if v == 9 |
| 11 | + return [steps] if v == 9 |
8 | 12 |
|
9 | | - DIRS |
| 13 | + return DIRS |
10 | 14 | .map { |dx,dy| [x+dx, y+dy] } |
11 | | - .flat_map { |nx, ny| find_trails(grid, v+1, nx, ny) } |
| 15 | + .flat_map { |nx, ny| find_trails(grid, nx, ny, v+1, [*steps, [nx,ny]]) } |
12 | 16 | end |
13 | 17 |
|
14 | 18 |
|
15 | 19 | input = File |
16 | 20 | .readlines('../input/10-sample.txt', chomp: true) |
17 | 21 | .map { _1.chars.map &:to_i } |
18 | 22 |
|
19 | | -p input |
20 | | - .each_with_index |
21 | | - .sum { |row,y| |
22 | | - row.each_index.sum { |x| find_trails(input, 0, x, y).size } |
23 | | - } |
| 23 | +trails = input.flat_map.with_index { |row,y| |
| 24 | + row.each_index.flat_map { |x| find_trails(input, x, y) } |
| 25 | +} |
| 26 | + |
| 27 | +p trails.group_by(&:first).sum { |_,trail| trail.map(&:last).uniq.size } |
| 28 | +p trails.size |
0 commit comments