advent_of_code/2024_13.rb
Code:
# Advent of Code 2024, Day 13: Claw Contraption
# https://adventofcode.com/2024/day/13
require_relative './helpers.rb'
def find(ax, ay, bx, by, px, py)
b = (py * ax - px * ay) / (by * ax - bx * ay).to_f
a = b.is_i? ? (px - b * bx) / ax.to_f : 0
a.is_i? && b.is_i? ? (a * 3 + b).to_i : 0
end
def part_one(rules)
rules.sum { |r| find(*r) }
end
def part_two(rules)
rules.sum { |r| find(*r[0, 4], r[4] + 10 ** 13, r[5] + 10 ** 13) }
end
def solve(data)
rules = data.each_slice(4).map { |a, b, c, _| [
a.split(/\+|\,|$/).select { |n| n.is_i? },
b.split(/\+|\,|$/).select { |n| n.is_i? },
c.split(/\=|\,|$/).select { |n| n.is_i? },
].flatten.map(&:to_i) }
[part_one(rules), part_two(rules)]
end
puts solve(get_dataset(year: 2024, day: 13, type: 'example'))
puts solve(get_dataset(year: 2024, day: 13, type: 'example_2'))
puts solve(get_dataset(year: 2024, day: 13, type: 'input'))
Output:
480
875318608908
875318608908
0
29517
103570327981381