Scala accessing an element of a sorted set

893 views Asked by At

I have a SortedSet[Int] object and I want to be able to find its median by retrieving mySet(sizeOfMySet/2), however it only says things like true and false. Is there some other way to retrieve elements?

2

There are 2 answers

4
Rex Kerr On
scala> val sorted = collection.immutable.SortedSet(5,3,1,7,2)
sorted: scala.collection.immutable.SortedSet[Int] = TreeSet(1, 2, 3, 5, 7)

scala> val half = sorted.size / 2
half: Int = 2

scala> val median = sorted.slice(half, half+1).headOption
median: Option[Int] = Some(3)

If you are sure the set is nonempty (and thus don't need an Option to cover that case) you can just use head.

0
Puneeth Reddy V On

Here is a way how you can get median over a collection of objects.

val sorted = collection.immutable.SortedSet(5,3,1,2,4,6)
val size = sorted.size
val median = if(size%2==0){
 // if there is a pair number of items, 
 // the median is the average of the two central elements
 (sorted.take(size/2+1).range(size/2, size/2+2).sum)/2.0
}
else{
 sorted.take(size/2+1).last
}