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?
Scala accessing an element of a sorted set
900 views Asked by user5045023 At
2
There are 2 answers
0
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
}
If you are sure the set is nonempty (and thus don't need an
Option
to cover that case) you can just usehead
.