From fd3fcb412ff00be1d73ca6dd2648e0b7c72b143c Mon Sep 17 00:00:00 2001 From: Ariejan de Vroom Date: Thu, 5 Dec 2024 08:44:30 +0100 Subject: [PATCH] Day 5 - Puzzle 2 --- lib/solutions/day_05.rb | 57 ++++++++++++++++++++++++++++++++++- spec/solutions/day_05_spec.rb | 2 +- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/lib/solutions/day_05.rb b/lib/solutions/day_05.rb index a1c2786..e5d9e8f 100644 --- a/lib/solutions/day_05.rb +++ b/lib/solutions/day_05.rb @@ -9,7 +9,13 @@ def part_one(input) end def part_two(input) - 0 + parse_input(input) + + @updates + .reject { |update| correct_order?(update) } + .map { |update| reorder(update) } + .map { |result| result[result.size / 2] } + .sum end def correct_order?(update) @@ -18,6 +24,14 @@ def correct_order?(update) end end + def reorder(update) + @relevant_order = @order + .select { |order| update.include?(order[0]) && update.include?(order[1]) } + + re = Reorder.new(@relevant_order) + re.reorder_update(update) + end + def parse_input(input) lines = input.split("\n") split_idx = lines.index('') @@ -26,3 +40,44 @@ def parse_input(input) @updates = lines[split_idx + 1..-1].map { |line| line.split(',').map(&:to_i) } end end + +class Reorder + def initialize(relevant_order) + @relevant_order = relevant_order + end + + def reorder_update(update) + graph = build_graph(@relevant_order) + sorted_order = topological_sort(graph) + update.sort_by { |num| sorted_order.index(num) } + end + + private + + def build_graph(relevant_order) + graph = Hash.new { |hash, key| hash[key] = [] } + relevant_order.each do |before, after| + graph[before] << after + end + graph + end + + def topological_sort(graph) + visited = {} + stack = [] + + graph.keys.each do |node| + topological_sort_util(node, visited, stack, graph) unless visited[node] + end + + stack.reverse + end + + def topological_sort_util(node, visited, stack, graph) + visited[node] = true + graph[node].each do |neighbor| + topological_sort_util(neighbor, visited, stack, graph) unless visited[neighbor] + end + stack << node + end +end diff --git a/spec/solutions/day_05_spec.rb b/spec/solutions/day_05_spec.rb index feb83de..d8dd778 100644 --- a/spec/solutions/day_05_spec.rb +++ b/spec/solutions/day_05_spec.rb @@ -12,7 +12,7 @@ describe '#part_two' do it 'calculates the correct solutions for part two' do - expect(subject.part_two(input)).to eq(0) + expect(subject.part_two(input)).to eq(123) end end end