AoC2024/day05/solution2.rb

45 lines
1.0 KiB
Ruby
Executable File

#!/usr/bin/env ruby
# frozen_string_literal: true
require 'pry'
def bubble_sort(array, rules)
return array if array.size <= 1
swap = true
while swap
swap = false
(array.length - 1).times do |x|
rule = rules.select { _1.include?(array[x]) and _1.include?(array[x + 1]) }.flatten
if rule != [array[x], array[x + 1]]
array[x], array[x + 1] = array[x + 1], array[x]
swap = true
end
end
end
array
end
# ifile = 'input.sample'
ifile = 'input'
input = File.readlines(ifile).map(&:strip).reject(&:empty?)
updates, rules = input.partition { _1.match?(',') }
rules.map! { _1.split('|').map(&:to_i) }
updates.map! { _1.split(',').map(&:to_i) }
updates.reject! do |update|
update.combination(2).map do |pair|
rule = rules.select { _1.include?(pair[0]) and _1.include?(pair[1]) }.flatten
next if rule.empty?
rule == pair
end.all?
end
updates.map! { |update| bubble_sort(update, rules) }
solution = updates.map { |update| update[update.size / 2] }.sum
# binding.pry
puts solution