Last active
December 5, 2024 18:49
-
-
Save carlwiedemann/d1c2ad286b68e9b0db1566c191980fa7 to your computer and use it in GitHub Desktop.
Advent of Code 2024 day005.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative "main" | |
module Day005 | |
INPUT = File.read('INPUT.txt') | |
rules_raw, updates_raw = INPUT.split("\n\n") | |
rules = rules_raw.split("\n").map { _1.split("|").map(&:to_i) } | |
updates = updates_raw.split("\n").map { _1.split(",").map(&:to_i) } | |
yea = rules.each_with_object(Hash.new { |h, k| h[k] = [] }) { _2[_1[0]].push(_1[1]) } | |
nay = rules.each_with_object(Hash.new { |h, k| h[k] = [] }) { _2[_1[1]].push(_1[0]) } | |
########## | |
# Part 1 # | |
########## | |
VALID = true | |
INVALID = false | |
segmented = updates.group_by do |u| | |
is_invalid = false | |
i = 0 | |
a = yea[u[i]] | |
b = nay[u[i]] | |
loop do | |
break if (i += 1) == u.length || (is_invalid = !a.include?(u[i]) || b.include?(u[i])) | |
a += yea[u[i]] | |
b += nay[u[i]] | |
end | |
!is_invalid | |
end | |
answer1 = segmented[VALID].sum { _1[_1.length / 2] } | |
pp answer1 | |
########## | |
# Part 2 # | |
########## | |
answer2 = segmented[INVALID].sum do |u| | |
i = 0 | |
while i < u.length | |
j = i + 1 | |
while j < u.length | |
a = yea[u[i]] | |
b = nay[u[i]] | |
u[i], u[j] = u[j], u[i] if !a.include?(u[j]) || b.include?(u[j]) | |
j += 1 | |
end | |
i += 1 | |
end | |
u[u.length / 2] | |
end | |
pp answer2 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment