Teodorico Levoff Teodorico Levoff - 1 month ago 12
Scala Question

Create a PriorityQueue that contains triples, and returns the minimum third element in Scala?

I have a Priority Queue in Scala that I define below. My goal is that when I call dequeue I get the triple that has the most minimum third element in that triple. I figured that using Ordering is the way to go, but I cannot seem to get it to work.

import scala.collection.mutable.PriorityQueue

def orderByWeight(lst : (Int, Int, Int)) = lst._3

val pq = new PriorityQueue[(Int, Int, Int)]()(Ordering.by(orderByWeight))

var x = ListBuffer((0,1,2), (0,2,3), (0,3,4))

x.map(i => pq.enqueue(i))

I am confused on what my
function should be. For the code above, the desired output if I call
should be
(0, 1, 2)
. Note
is ordered at random. Any ideas?


If you want all the 3-tuples dequeued in order of smalled 3rd element to largest, I think this is all you need.

val pq = PriorityQueue[(Int, Int, Int)]()(Ordering.by(-_._3))

If you need an ordered output in case of 3rd-element ties, you can expand it.

var x = ListBuffer((0,1,2), (0,2,3), (0,3,4), (1,0,2))
val pq = PriorityQueue(x:_*)(Ordering[(Int, Int)].on(x => (-x._3, -x._2)))