首页 > 解决方案 > 计算某个元素的组数

问题描述

我有一个列表,我需要计算某些元素的组数(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

标签: scalacollections

解决方案


为什么不对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 会话,其中包含一些使用示例。


推荐阅读