1
0
Fork 0
advent-of-code-2024/5-2.rb
2024-12-06 15:16:07 -05:00

61 lines
1,008 B
Ruby
Executable file

#!/usr/bin/env ruby
problem = 5
input = File.readlines("#{problem}.input").map(&:strip)
#input = DATA.read.split("\n")
split = input.index("")
rules = input[0...split].map { _1.split("|").map(&:to_i) }
page_sets = input[split+1..].map { _1.split(",").map(&:to_i) }
result = page_sets.select do |page_set|
rules
.select { |a| (page_set & a).sort == a.sort }
.any? { |(a, b)| page_set.index(a) > page_set.index(b) }
end.map do |page_set|
matched_rules = rules
.select { |a| (page_set & a).sort == a.sort }
.reduce(Hash.new { |h, k| h[k] = Array.new }) { |a, (k, v)| a[k] << v; a }
page_set.sort do |a, b|
if matched_rules[a].include?(b)
-1
elsif matched_rules[b].include?(a)
1
else
0
end
end
end.map { _1[_1.size / 2] }.sum
p result
__END__
47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47