bsky
bsky

Reputation: 20222

Structure sorted by values instead of keys

In Scala, I need to create a structure which contains the following:

Because an element is uniquely identified by the combination of the Bitset representing occupied cells and the Int representing the last cell occupied, I tried using the following:

var tm = TreeMap.empty[Path, Int]

Where Path is:

case class Path(occupied: BitSet, last: Int)

However, the issue is that I want to sort the elements in the TreeMap by their cost(so by their Value). This is apparently not possible for TreeMap.

So can I have a structure where I sort the elements by Value rather than Key?

Upvotes: 0

Views: 42

Answers (1)

0__
0__

Reputation: 67280

I think you look for a sorted-set then:

import scala.collection.immutable.BitSet
import scala.collection.immutable.SortedSet

case class Path(occupied: BitSet, last: Int, cost: Int)

implicit val pathOrd = Ordering.by((p: Path) => p.cost)

SortedSet.empty[Path]

Assuming that cost is a field of Path. If the cost is calculated from the Path, you could also define:

case class Path(occupied: BitSet, last: Int) {
  def cost: Int = ???
}

Upvotes: 2

Related Questions