Snippet

advent_of_code/2024_10.rb
Code:
# Advent of Code 2024, Day 10: Hoof It

# https://adventofcode.com/2024/day/10

require_relative './helpers.rb'

def search(point, grid, check_seen = true, path = [], seen = [])
  return 0 if check_seen && seen.include?(point)
  seen.push(point) if check_seen
  path.push(point)
  this = get_grid(grid, point)
  return 1 if this == 9
  lt, rt = [point.x - 1, point.y].to_p, [point.x + 1, point.y].to_p
  up, dn = [point.x, point.y - 1].to_p, [point.x, point.y + 1].to_p
  args = [grid, check_seen, path, seen]
  return [
    get_grid(grid, lt) == this + 1 ? search(lt, *args) : 0,
    get_grid(grid, rt) == this + 1 ? search(rt, *args) : 0,
    get_grid(grid, up) == this + 1 ? search(up, *args) : 0,
    get_grid(grid, dn) == this + 1 ? search(dn, *args) : 0,
  ]
end

def part_one(grid)
  find_grid(grid, 0).map { |start| search(start, grid, true) }.flatten.sum
end

def part_two(grid)
  find_grid(grid, 0).map { |start| search(start, grid, false) }.flatten.sum
end

def solve(data)
  data = data.map{ |row| row.chomp.chars.map(&:to_i) }
  [part_one(data), part_two(data)]
end

puts solve(get_dataset(year: 2024, day: 10, type: 'example'))
puts solve(get_dataset(year: 2024, day: 10, type: 'example_2'))
puts solve(get_dataset(year: 2024, day: 10, type: 'input'))
Output:
36
81
1
16
461
875