Skip to content

Commit

Permalink
Add 2024, day 5
Browse files Browse the repository at this point in the history
  • Loading branch information
bewuethr committed Dec 6, 2024
1 parent eb5b3a0 commit ac56613
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
15 changes: 15 additions & 0 deletions 2024/day05/day05a
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env ruby

lines = File.readlines(ARGV[0]).map(&:chomp)
blank_idx = lines.index("")

rules = lines[...blank_idx].map { _1.split("|").map(&:to_i) }.to_set
pages = lines[blank_idx + 1..].map { _1.split(",").map(&:to_i) }

total = pages.select do |list|
list.each_with_index.all? do |page, idx|
list[idx + 1..].all? { rules.include?([page, _1]) || !rules.include?([_1, page]) }
end
end.map { _1[_1.length / 2] }.sum

puts total
31 changes: 31 additions & 0 deletions 2024/day05/day05b
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env ruby

def is_correct?(list, rules)
list.each_with_index.all? do |page, idx|
list[idx + 1..].all? { rules.include?([page, _1]) || !rules.include?([_1, page]) }
end
end

def swap(list, idx_a, idx_b)
list[idx_a], list[idx_b] = list[idx_b], list[idx_a]
end

lines = File.readlines(ARGV[0]).map(&:chomp)
blank_idx = lines.index("")

rules = lines[...blank_idx].map { _1.split("|").map(&:to_i) }.to_set
pages = lines[blank_idx + 1..].map { _1.split(",").map(&:to_i) }

incorrect_pages = pages.reject { is_correct?(_1, rules) }

total = incorrect_pages.sum do |list|
until is_correct?(list, rules)
(0...list.length).to_a.combination(2).each do |a, b|
swap(list, a, b) if rules.include?([list[b], list[a]])
end
end

list[list.length / 2]
end

puts total

0 comments on commit ac56613

Please sign in to comment.