gpt4 book ai didi

scala - 将距离小于 x 的 List 元素分组

转载 作者:行者123 更新时间:2023-12-04 18:41:11 25 4
gpt4 key购买 nike

我试图找出一种根据元素之间的 x 距离对列表中的所有对象进行分组的方法。

例如,如果距离是 1然后

List(2,3,1,6,10,7,11,12,14)

会给
List(List(1,2,3), List(6,7), List(10,11,12), List(14))

我只能提出棘手的方法和循环,但我想必须有一个更清洁的解决方案。

最佳答案

您可以尝试对列表进行排序,然后在其上使用 foldLeft。基本上是这样的

  def sort = {
val l = List(2,3,1,6,10,7,11,12,14)
val dist = 1
l.sorted.foldLeft(List(List.empty[Int]))((list, n) => {
val last = list.head
last match {
case h::q if Math.abs(last.head-n) > dist=> List(n) :: list
case _ => (n :: last ) :: list.tail
}
}
)
}

结果似乎没问题,但反过来了。如果需要,在列表上调用“reverse”。代码变成
    val l = List(2,3,1,6,10,7,11,12,14)
val dist = 1
val res = l.sorted.foldLeft(List(List.empty[Int]))((list, n) => {
val last = list.head
last match {
case h::q if Math.abs(last.head-n) > dist=> List(n) :: (last.reverse :: list.tail)
case _ => (n :: last ) :: list.tail
}
}
).reverse

关于scala - 将距离小于 x 的 List 元素分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26145189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com