Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created November 29, 2015 16:24
Show Gist options
  • Save fancellu/e1d1cc43e8a36a85a88b to your computer and use it in GitHub Desktop.
Save fancellu/e1d1cc43e8a36a85a88b to your computer and use it in GitHub Desktop.
Example of using a min heap with case class
object MinHeap {
case class Dog(age:Int, name:String) extends Ordered[Dog]{
def compare(that: Dog) = - this.age.compareTo(that.age)
}
val minHeap = scala.collection.mutable.PriorityQueue.empty[Dog]
//> minHeap : scala.collection.mutable.PriorityQueue[MinHeap.Dog] = PriorityQue
//| ue()
minHeap+=Dog(1,"Rusty") //> res0: MinHeap.minHeap.type = PriorityQueue(Dog(1,Rusty))
minHeap+=Dog(12,"Max") //> res1: MinHeap.minHeap.type = PriorityQueue(Dog(1,Rusty), Dog(12,Max))
minHeap+=Dog(5,"Spot") //> res2: MinHeap.minHeap.type = PriorityQueue(Dog(1,Rusty), Dog(12,Max), Dog(5,
//| Spot))
// note, the toString of PQ doesn't obey order
minHeap.head //> res3: MinHeap.Dog = Dog(1,Rusty)
minHeap+=Dog(0,"Pup") //> res4: MinHeap.minHeap.type = PriorityQueue(Dog(0,Pup), Dog(1,Rusty), Dog(5,S
//| pot), Dog(12,Max))
minHeap.head //> res5: MinHeap.Dog = Dog(0,Pup)
// don't use toList etc if you want the order to be obeyed, use dequeueAll. Note I clone first, as dequeuAll does mutate
minHeap.clone.dequeueAll //> res6: scala.collection.immutable.IndexedSeq[MinHeap.Dog] = Vector(Dog(0,Pup)
//| , Dog(1,Rusty), Dog(5,Spot), Dog(12,Max))
minHeap.dequeue() //> res7: MinHeap.Dog = Dog(0,Pup)
minHeap.clone.dequeueAll //> res8: scala.collection.immutable.IndexedSeq[MinHeap.Dog] = Vector(Dog(1,Rust
//| y), Dog(5,Spot), Dog(12,Max))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment