Skip to content

Commit

Permalink
Merge pull request #22 from ngng628/priority-queue
Browse files Browse the repository at this point in the history
Improve PriorityQueue
  • Loading branch information
hakatashi authored Sep 7, 2023
2 parents 2832b71 + db582f2 commit 99fc2f8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
16 changes: 16 additions & 0 deletions spec/priority_queue_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,22 @@ describe "PriorityQueue" do
q.pop.should eq nil
end

describe ".pop!" do
it "pops values in priority order. Raises Enumerable::NotFoundError if queue is empty." do
q = PriorityQueue(Int32).max
q << 5 << 6 << 1 << 3 << 2 << 8 << 7 << 4
q.pop!.should eq 8
q.pop!.should eq 7
q.pop!.should eq 6
q.pop!.should eq 5
q.pop!.should eq 4
q.pop!.should eq 3
q.pop!.should eq 2
q.pop!.should eq 1
expect_raises(Enumerable::EmptyError) { q.pop! }
end
end

it "initialized by elements in *enumerable*" do
q = PriorityQueue.max([5, 6, 1, 3, 2, 8, 7, 4])
q.pop.should eq 8
Expand Down
12 changes: 10 additions & 2 deletions src/priority_queue.cr
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@ module AtCoder
end

# Pushes value into the queue.
def push(v : T)
# This method returns self, so several calls can be chained.
def push(v : T) : self
@heap << v
index = @heap.size - 1
while index != 0
Expand All @@ -125,10 +126,11 @@ module AtCoder
@heap[parent], @heap[index] = @heap[index], @heap[parent]
index = parent
end
self
end

# Alias of `push`
def <<(v : T)
def <<(v : T) : self
push(v)
end

Expand Down Expand Up @@ -158,6 +160,12 @@ module AtCoder
ret
end

# Pops value from the queue.
# Raises `Enumerable::EmptyError` if queue is of 0 size.
def pop!
pop || raise Enumerable::EmptyError.new
end

# Yields each item in the queue in comparator's order.
def each(&)
@heap.sort { |a, b| @compare_proc.call(a, b) ? 1 : -1 }.each do |e|
Expand Down

0 comments on commit 99fc2f8

Please sign in to comment.