Skip to content

Commit

Permalink
Day 5 - Puzzle 2
Browse files Browse the repository at this point in the history
  • Loading branch information
ariejan committed Dec 5, 2024
1 parent 78ccc1e commit fd3fcb4
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
57 changes: 56 additions & 1 deletion lib/solutions/day_05.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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('')
Expand All @@ -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
2 changes: 1 addition & 1 deletion spec/solutions/day_05_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit fd3fcb4

Please sign in to comment.