2015-06-24 22 views

回答

2
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) 

如果您確定集合爲非空(因此不需要一個Option覆蓋的話),你可以只使用head

+0

我剛剛意識到也許SortedSet不適合我,因爲我可以有重複的元素。有沒有SortedList? – user5045023

+0

@ user5045023是的。或者,您可以使用'SortedSet((Item,NumTimes))' – Daenyth

+0

雖然這是正確的,但值得注意的是'slice'將迭代第一個'half'元素,它不會跳到正確的位置。 (至少從scala 2.11.8的代碼來判斷 - 'slice'來自'IterableLike',它調用('iterator drop lo')[https://github.com/scala/scala/blob/v2.11.8 /src/library/scala/collection/IterableLike.scala#L117])。 –

1

這是一種如何獲取對象集合中位數的方法。

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 
}