Skip to content

Instantly share code, notes, and snippets.

@carlwiedemann
Last active December 3, 2024 05:59
Show Gist options
  • Save carlwiedemann/9aee5c344140322a9c9fea853c2d5e2c to your computer and use it in GitHub Desktop.
Save carlwiedemann/9aee5c344140322a9c9fea853c2d5e2c to your computer and use it in GitHub Desktop.
Advent of Code 2024 day003.rb
require_relative "main"
module Day003
INPUT = File.read('INPUT.txt')
##########
# Part 1 #
##########
MUL_REGEX = /mul\(\d+,\d+\)/
mul_to_prod = ->(s) { s.split(',').map { _1.gsub(/[^\d]/, '').to_i }.reduce(:*) }
answer1 = INPUT.scan(MUL_REGEX).sum(&mul_to_prod)
pp answer1
##########
# Part 2 #
##########
fetch_indices = ->(string, regex) do
i, ii = -1, []
while (i = string.index(regex, i + 1))
ii.push(i)
end
ii
end
mul_ii = fetch_indices.call(INPUT, MUL_REGEX)
off_ii = fetch_indices.call(INPUT, /don't\(\)/)
on_ii = fetch_indices.call(INPUT, /do\(\)/)
i = 0
answer2 = 0
on = true
while i < INPUT.length
if mul_ii.first == i
mul_i = mul_ii.shift
answer2 += mul_to_prod.call(INPUT[mul_i..].match(MUL_REGEX)[0]) if on
elsif off_ii.first == i
on = false
off_ii.shift
elsif on_ii.first == i
on = true
on_ii.shift
end
i += 1
end
pp answer2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment