advent_of_code/2024_5.rb
Code:
# Advent of Code 2024, Day 5: Print Queue
# https://adventofcode.com/2024/day/5
require_relative './helpers.rb'
def is_valid?(b, r)
r.map { |i, j| [b.ix(i), b.ix(j)].compact.as { |c| c.size == 2 ? c == c.sort : 1 } }.all?
end
def part_one(bs, r)
bs.filter { |b| is_valid?(b, r) }.map { |b| b[b.size / 2] }.sum
end
def part_two(bs, r)
bs.reject { |b| is_valid?(b, r) }.map { |b|
(0...b.size).each { |i| (i + 1...b.size).each { |j| b[i], b[j] = b[j], b[i] if r.has? [b[j], b[i]] } }
b[b.size / 2]
}.sum
end
def solve(data)
b = data.filter { |l| l.has?(',') }.map { |l| l.split(',').map(&:to_i) }
r = data.filter { |l| l.has?('|') }.map { |l| l.split('|').map(&:to_i) }
[part_one(b, r), part_two(b, r)]
end
puts solve(get_dataset(year: 2024, day: 5, type: 'example'))
puts solve(get_dataset(year: 2024, day: 5, type: 'input'))
Output:
143
123
6242
5169