Skip to content

Instantly share code, notes, and snippets.

@wishdev
Created October 2, 2009 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wishdev/199934 to your computer and use it in GitHub Desktop.
Save wishdev/199934 to your computer and use it in GitHub Desktop.
require 'pqueue'
pq = PQueue.new proc{|x, y| x.compare(y)}
#Do either the Array monkey_patch or Record concept
class Array
attr_reader :insert_time
def compare(other_record)
#We want to return TRUE if this record should take
#priority over the other record in the queue
if self[0] == other_record[0]
insert_time > other_record.insert_time
else
self[0] < other_record[0]
end
end
def queue(pq)
@insert_time = Time.now()
pq.push(self)
end
end
x = [1, 2, 3, 4]
x.queue(pq)
sleep 1
y = [1, 2, 3, 4]
y.queue(pq)
until pq.empty?
itm = pq.pop
p itm
p itm.insert_time
end
class Record
attr_accessor :f1, :f2, :f3, :f4
attr_reader :insert_time
def initialize(f1, f2, f3, f4)
@f1, @f2, @f3, @f4 = f1, f2, f3, f4
end
def compare(other_record)
#We want to return TRUE if this record should take
#priority over the other record in the queue
if f1 == other_record.f1
insert_time > other_record.insert_time
else
f1 < other_record.f1
end
end
def queue(pq)
@insert_time = Time.now()
pq.push(self)
end
end
pq.clear
x = Record.new(1, 2, 3, 4)
x.queue(pq)
sleep 1
y = Record.new(1, 5, 6, 7)
y.queue(pq)
until pq.empty?
p pq.pop
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment