Class: PriorityQueue

Inherits:
Heap
  • Object
show all
Defined in:
lib/data_structures/priority_queue.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Heap

#empty?, #extract, #initialize, #insert_mutliple, #length, #peek, #to_a

Constructor Details

This class inherits a constructor from Heap

Class Method Details

.from_array(array) ⇒ Object



4
5
6
7
8
# File 'lib/data_structures/priority_queue.rb', line 4

def self.from_array(array)
  nodes = array.map { |arr| PriorityQueueNode.new(arr.first, arr.last) }
  heap = super(nodes)
  from_heap(heap)
end

.from_hash(hash) ⇒ Object



10
11
12
13
14
# File 'lib/data_structures/priority_queue.rb', line 10

def self.from_hash(hash)
  nodes = hash.map { |k, v| PriorityQueueNode.new(k, v) }
  heap = self.superclass.from_array(nodes)
  from_heap(heap)
end

Instance Method Details

#find(data) ⇒ Object



29
30
31
32
33
# File 'lib/data_structures/priority_queue.rb', line 29

def find(data)
  return nil if @store.empty?
  @store.each { |node| return node if node.send(:data) == data }
  nil
end

#include?(data) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
# File 'lib/data_structures/priority_queue.rb', line 35

def include?(data)
  return nil if @store.empty?
  @store.each { |node| return true if node.send(:data) == data }
  false
end

#insert(data, priority) ⇒ Object



24
25
26
27
# File 'lib/data_structures/priority_queue.rb', line 24

def insert(data, priority)
  node = PriorityQueueNode.new(data, priority)
  super(node)
end

#inspectObject



20
21
22
# File 'lib/data_structures/priority_queue.rb', line 20

def inspect
  "Priority Queue: head=#{self.peek || 'nil'}, length=#{self.length}"
end

#merge(other_queue) ⇒ Object

Raises:

  • (ArgumentError)


41
42
43
44
45
46
# File 'lib/data_structures/priority_queue.rb', line 41

def merge(other_queue)
  raise ArgumentError.new("May only merge with a Priority Queue. You passed a #{other_queue.class}.") unless other_queue.is_a?(PriorityQueue)
  array = self.send(:store) + other_queue.send(:store)
  heap = self.class.superclass.from_array(array)
  self.class.send(:from_heap, heap)
end

#to_sObject



16
17
18
# File 'lib/data_structures/priority_queue.rb', line 16

def to_s
  "Priority Queue: head=#{self.peek || 'nil'}, length=#{self.length}"
end