Skip to content

Commit

Permalink
Add #each_with_priority
Browse files Browse the repository at this point in the history
  • Loading branch information
mhib committed Jan 31, 2023
1 parent bdd1278 commit cd0c743
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
18 changes: 17 additions & 1 deletion lib/pairing_heap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -261,12 +261,20 @@ def get_priority_if_exists(elem)

# Returns enumerator of elements.
# @note There are no order guarantees.
# @return [Enumerator]
# @return [Enumerator<Object>]
def each
return to_enum(__method__) { size } unless block_given?
@nodes.each_value { |node| yield node.elem }
end

# Returns enumerator of elements.
# @note There are no order guarantees.
# @return [Enumerator<Array(Object, Object)>]
def each_with_priority
return to_enum(__method__) { size } unless block_given?
@nodes.each_value { |node| yield [node.elem, node.priority] }
end

private

include MergePairs
Expand Down Expand Up @@ -406,6 +414,14 @@ def each
NodeVisitor.visit_node(@root) { |x| yield x.elem }
end

# @return [Enumerator<Array(object, object)>]
# Returns enumerator of elements.
# @note There are no order guarantees.
def each_with_priority
return to_enum(__method__) { size } unless block_given?
NodeVisitor.visit_node(@root) { |x| yield [x.elem, x.priority] }
end

private

include MergePairs
Expand Down
14 changes: 14 additions & 0 deletions test/pairing_heap_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,20 @@ def included(ancestor)
end
end

describe "#each_with_priority" do
it "returns all elements" do
1.upto(500) do |i|
@queue.push(i)
end
@queue.pop
_(@queue.each_with_priority.to_set).must_equal(Set.new((2..500).map { |x| [x, x] }))
end

it "returns no elements when empty" do
_(@queue.each_with_priority.to_a).must_equal([])
end
end

describe "#peek_with_priority" do
it "returns tuple with priority" do
@queue.push(1, 2)
Expand Down

0 comments on commit cd0c743

Please sign in to comment.