Skip to content

Instantly share code, notes, and snippets.

@starmer
Created August 13, 2012 02:39
Show Gist options
  • Select an option

  • Save starmer/3336500 to your computer and use it in GitHub Desktop.

Select an option

Save starmer/3336500 to your computer and use it in GitHub Desktop.
PriorityQueue
require 'set'
class PriorityQueue
def initialize
@pq = SortedSet.new
end
def insert key, value
entry = find(key) || Entry.new(key)
entry.add(value)
@pq << entry
end
def find(search_key)
found = nil
@pq.each do |entry|
if entry.key == search_key
found = entry
end
end
found
end
def remove
entry = @pq.first
@pq.delete(entry)
entry_value = entry.remove()
if entry.size > 0
@pq << entry
end
entry_value
end
end
class Entry
include Comparable
attr_reader :key, :list
def initialize(key)
@key = key
@list = []
end
def add(value)
list << value
end
def remove()
list.shift
end
def size()
list.size
end
def <=>(other)
other.key <=> self.key
end
end
require 'priority_queue.rb'
describe PriorityQueue do
before { @pq = PriorityQueue.new }
it 'can pull the highest priority item' do
@pq.insert 1, "A"
@pq.insert 25, "B"
@pq.insert 1, "C"
@pq.insert 25, "D"
@pq.remove().should eq "B"
@pq.remove().should eq "D"
@pq.remove().should eq "A"
@pq.remove().should eq "C"
end
describe Entry do
it 'should compare' do
e = Entry.new(2)
e2 = Entry.new(1)
value = e.<=> e2
value.should eq(-1)
end
it 'should act like a queue' do
e = Entry.new(2)
e.add "A"
e.add "B"
e.add "C"
e.remove.should eq "A"
e.remove.should eq "B"
e.remove.should eq "C"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment