Snippet

advent_of_code/2024_11.rb
Code:
# Advent of Code 2024, Day 11: Plutonian Pebbles

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

require_relative './helpers.rb'

@cache = {}

def blink(pebble, left)
  return 1 if left == 0
  return @cache[[pebble, left]] if @cache[[pebble, left]]
  if pebble == 0
    n = blink(1, left - 1)
  else
    d = pebble.digits
    if d % 2 == 0
      f = 10 ** d.div(2)
      n = blink(pebble.div(f), left - 1) + blink(pebble % f, left - 1)
    else
      n = blink(pebble * 2024, left - 1)
    end
  end
  @cache[[pebble, left]] = n
  return n
end

def part_one(pebbles)
  pebbles.map { |pebble| blink(pebble, 25) }.sum
end

def part_two(pebbles)
  pebbles.map { |pebble| blink(pebble, 75) }.sum
end

def solve(data)
  data = data[0].split(' ').map(&:to_i)
  [part_one(data), part_two(data)]
end

puts solve(get_dataset(year: 2024, day: 11, type: 'example'))
puts solve(get_dataset(year: 2024, day: 11, type: 'example_2'))
puts solve(get_dataset(year: 2024, day: 11, type: 'input'))
Output:
125681
149161030616311
55312
65601038650482
202019
239321955280205