This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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