如何将一个scala数组中的连续整数分组?
问题描述:
比方说,我有如下所示的数组:如何将一个scala数组中的连续整数分组?
1 2 3 4 5 6 7 8 9 1 2 3 4 5 1 2 3 4
我要连续编号的多个子阵列的每个连续对的,其总和小于10
1 2 3 4 5, 6, 7, 8, 9, 1 2 3 4 5 1 2 3 4
如何编写它在功能习惯方式的斯卡拉?
// example no. 1
>Array(1, 2, 3, 4, 5, 6)...???
res0: List(Array(1, 2, 3, 4, 5), Array(6))
// example no. 2
>Array(3, 8, 1, 9, 1, 3)...???
res1: List(Array(3), Array(8, 1), Array(9), Array(1, 3))
答
做一个foldRight
使得它更容易使用head
和tail
建设所产生的List
。
val grouped = Array(3,8,1,9,1,3).foldRight(List.empty[Array[Int]]){case (n,acc) =>
if (acc.isEmpty) List(Array(n))
else if (acc.head.head + n < 10) n +: acc.head :: acc.tail
else Array(n) :: acc
} // List(Array(3), Array(8, 1), Array(9), Array(1, 3))
+0
酷!谢谢 :) – gurghet
答
这应该工作(虽然这是一个非常低效的方式):
def group(threshold: Int)(seq: Seq[Int]): Seq[Seq[Int]] =
seq.reverse.tails.find(_.sum < threshold) match {
case None => Nil
case Some(Nil) => Nil
case Some(subSeq) =>
subSeq.reverse +: group(threshold)(seq.drop(subSeq.size))
}
group(10)(Array(3, 8, 1, 9, 1, 3))
List(Array(3), Array(8, 1), Array(9), Array(1, 3))
它与反应x和类别理论有什么关系? – adamwy
它可以用反应x或类别理论解决 – gurghet
我看不出任何相关性。目前还不清楚你想达到什么目的,你想分割数组到低于或高于给定的阈值? – adamwy