Skip to content

Commit

Permalink
mark: making it a bit more readable
Browse files Browse the repository at this point in the history
  • Loading branch information
mneedham committed Dec 19, 2012
1 parent 61d1b2f commit ee0988c
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions prims_heap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ def nodes_left_to_cover

heap = PriorityQueue.new
nodes_left_to_cover.each do |node|
cheapest_nodes = get_edges(adjacency_matrix, node-1).select { |_, other_node_index| @nodes_spanned_so_far.include?(other_node_index + 1) } || []
cheapest_nodes = get_edges(adjacency_matrix, node-1).
select { |_, other_node_index| @nodes_spanned_so_far.include?(other_node_index + 1) } || []

cheapest = cheapest_nodes.inject([]) do |all_edges, (weight, index)|
all_edges << { :start => node, :end => index + 1, :weight => weight }
Expand All @@ -52,13 +53,13 @@ def nodes_left_to_cover
end

while !nodes_left_to_cover.empty?
cheapest = heap.delete_min
spanning_tree_cost += cheapest[1]
@nodes_spanned_so_far << cheapest[0]
cheapest_node, weight = heap.delete_min
spanning_tree_cost += weight
@nodes_spanned_so_far << cheapest_node

edges_with_potential_change = get_edges(adjacency_matrix, cheapest[0]-1).reject { |_, node_index| @nodes_spanned_so_far.include?(node_index + 1) }
edges_with_potential_change = get_edges(adjacency_matrix, cheapest_node-1).reject { |_, node_index| @nodes_spanned_so_far.include?(node_index + 1) }
edges_with_potential_change.each do |weight, node_index|
heap.change_priority(node_index+1, [heap.priority(node_index+1), adjacency_matrix[cheapest[0]-1][node_index]].min)
heap.change_priority(node_index+1, [heap.priority(node_index+1), adjacency_matrix[cheapest_node-1][node_index]].min)
end
end

Expand Down

0 comments on commit ee0988c

Please sign in to comment.