基于相邻元素之间的差异在scala中拆分列表 [英] split list in scala based on diff between neighbouring elements

查看:31
本文介绍了基于相邻元素之间的差异在scala中拆分列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何根据相邻元素之间的差异在scala中拆分列表.例如给定 List(1,3,6,10,12,14) 和差异 3,函数将返回 List(List(1,3),List(6),List(10,12,14)).

How do we split list in scala based on difference between neighbouring elements. For example given List(1,3,6,10,12,14) and difference 3, the function would return List(List(1,3),List(6),List(10,12,14)).

我们可以使用 foldLeft 来做到这一点吗?我正在尝试创建一个函数

Can we user foldLeft to do that? I was trying to create a function

def splitDiff(list:List[Int],diff:Int) = 
     def func(list:List[List[Int]],m:Int):List[List[Int]] = //compare with last element
     list.foldLeft(List(List(0))).foldLeft(func)

但是内部函数好像很难?有什么帮助吗?

But the inner function seems difficult? Any help?

推荐答案

嗯,我有一个解决方案,但我怀疑有人可以做得更好:

Hmm, I have a solution, but I suspect one can do better:

(test.head :: test).sliding(2).toList.map( (pair: List[Int]) => (pair(1), pair(1) - pair(0)) )
                   .foldLeft(List(List.empty[Int])){ (acc, pair) => 
     if (pair._2 < 3) (pair._1 :: acc.head) :: acc.tail else List(pair._1) :: acc }

请注意,这会以双重反转"顺序给出结果:

Note that this gives results in "doubly-reversed" order:

res3: List[List[Int]] = List(List(14, 12, 10), List(6), List(3, 1))

可以通过在函数末尾添加 .map(_.reverse).reverse 来纠正.

Which can be corrected by adding .map(_.reverse).reverse to the end of the function.

编辑 - 替代尝试:

def func(is: List[Int], diff: Int): List[List[Int]] = {
  def loop(is: List[Int], prev: Int, acc: List[List[Int]]): List[List[Int]] = is match {
    case Nil => acc
    case h :: t if (h - prev < diff) => loop(t, h, (h :: acc.head) :: acc.tail)
    case h :: t => loop(t, h, List(h) :: acc)
  }

  loop(is, is.head, List(List.empty[Int]))
}

再次给出双反转形式的解.

Again, gives solution in doubly-reversed form.

这篇关于基于相邻元素之间的差异在scala中拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆