我有一個串列,我需要計算某些元素(1 或 0)的組數。
(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1)
val count1Grp = daysSequence.foldLeft(List[Int]()){(acc, elem) =>
if(acc.isEmpty) elem :: acc else if(acc.head == elem) acc else elem :: acc
}
.count(_ == 1)
val count0Grp = daysSequence.foldLeft(List[Int]()){(acc, elem) =>
if(acc.isEmpty) elem :: acc else if(acc.head == elem) acc else elem :: acc
}
.count(_ == 0)
我折疊相似的鄰居元素,然后計算剩下的內容。并得到
count1Grp = 1
count0Grp = 1
另一個例子。兩行結果相同。
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(-1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)
count1Grp = 1
count0Grp = 2
但是,如果我需要將 2 個或更多相似元素一起量化為一個組,我該怎么做?在第一種情況下 0 不符合標準,應該導致
count1Grp = 1
count0Grp = 0
uj5u.com熱心網友回復:
為什么不獲取Map集合中每個組的計數?那么只需要一次遍歷。
def groupCount[A](xs : Seq[A]
,grpSize : Int = 1
,acc : Map[A,Int] = Map[A,Int]()
): Map[A,Int] = xs match {
case Seq() => acc
case hd : _ =>
val (grp,rest) = xs.span(_ == hd)
if (grp.size < grpSize)
groupCount(rest, grpSize, acc)
else
groupCount(rest, grpSize, acc (hd -> (acc.getOrElse(hd,0) 1)))
}
這是一個包含一些使用示例的Scastie 會話。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344781.html
