Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a collection with PartialOrdering?

I need to order a collection of envelopes. Each envelope is described with its height and width. Envelope1 is smaller than envelope2 if it can be inserted in envelope2. If envelope1 cannot be inserted in envelope2 and vice versa, then they couldn't be compared.

How can i order these envelopes in scala? I couldn't find any information about that on the internet.

Here is some code I have:

object EnvelopeOrdering extends PartialOrdering[(Int, Int)] {
  override def tryCompare(x: (Int, Int), y: (Int, Int)): Option[Int] = {
    if (x._1 < y._1 && x._2 < y._2) return Some(1)
    if (x._1 > y._1 && x._2 > y._2) return Some(-1)
    if (x._1 == y._1 && x._2 == y._2) return Some(0)
    None
  }

  override def lteq(x: (Int, Int), y: (Int, Int)): Boolean = x._1 < y._1 && x._2 < y._2
}
like image 695
Mysterion Avatar asked Nov 10 '22 04:11

Mysterion


1 Answers

What you are interested in is topological sort and there is a classical algorithm to perform it with complexity in the order of number of edges. In your case you will have an edge between two envelopes if and only if the first one is smaller(and the edge should point from the smaller to the bigger one).

like image 117
Ivaylo Strandjev Avatar answered Nov 15 '22 07:11

Ivaylo Strandjev