scala - 计算某个元素的组数
问题描述
我有一个列表,我需要计算某些元素的组数(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
解决方案
为什么不对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 会话,其中包含一些使用示例。
推荐阅读
- bootstrap-4 - 手动安装 Bootstrap4
- oracle - 如何计算 ORACLE 中 2 列之和的平均值?
- python - 从嵌套为python中字典值的两个列表中检索数据的最有效方法
- python - Bokeh 可以检测屏幕尺寸并重塑移动设备的布局吗?
- c++ - 交换两个对象的两个属性的值
- python - txt 与 dict 的 str 成 dict
- amazon-cloudwatch - CloudWatch Log Insights 中的多方面时间序列可视化
- compiler-construction - 转译/代码生成 - 变量声明问题
- javafx - 尝试使用 FXML 文件进行编译时,JavaFX 程序不起作用
- python - 错误:[Index(['...'], dtype='object')] 中没有一个在 [index] 中