Created
December 10, 2024 14:22
-
-
Save swanandp/8b0d39eb4177531c55f554b5e3435a42 to your computer and use it in GitHub Desktop.
AOC 2024 Day 10, easy count paths/count destinations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
def neighbours(input, i, j) | |
# @formatter:off | |
@deltas ||= [ | |
[-1, 0], | |
[0, -1], [0, 1], | |
[1, 0], | |
] | |
# @formatter:on | |
r = input.length | |
c = input[0].length | |
@deltas.map { |di, dj| | |
[i + di, j + dj] | |
}.select { |ix, jx| | |
0 <= ix && ix < r && # row within bounds | |
0 <= jx && jx < c # column within bounds | |
} | |
end | |
input = DATA.read.strip.split("\n").map { |l| l.split("").map { |c| c == "." ? nil : c.to_i } } | |
def find_zeroes(input) | |
trail_heads = [] | |
input.each_with_index.map do |r, i| | |
r.each_with_index do |c, j| | |
if c == 0 | |
trail_heads << [i, j] | |
end | |
end | |
end | |
trail_heads | |
end | |
def hike(input, i, j) | |
cell = input[i][j] | |
if cell == 9 | |
return [[i, j]] | |
end | |
walkable = neighbours(input, i, j).select { |ni, nj| | |
input[ni][nj] == cell + 1 | |
} | |
walkable.flat_map { |ni, nj| | |
hike(input, ni, nj) | |
} | |
end | |
zeroes = find_zeroes(input) | |
pp zeroes.sum { |zi, zj| hike(input, zi, zj).length } # should be 81 | |
__END__ | |
89010123 | |
78121874 | |
87430965 | |
96549874 | |
45678903 | |
32019012 | |
01329801 | |
10456732 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment