问题描述
我当前正在尝试提取列表中相差1的邻居。例如,如果我的列表是这样的:
I'm currently trying to extract neighbours in a List who differ by 1. For example if I had my List like this:
List(1,2,3,7,8,10,13,14)
//By extracting I want to get:
List(
List(1,2,3),
List(7,8),
List(10),
List(13,14)
)
我自己通过foldLeft尝试过,我感觉自己已经很近了,但是到目前为止。谁能帮我?有什么建议么? ^^
非常感谢! :)
I've tried it myself by doing foldLeft, I felt like I was close but yet so far. Can anyone help me? Any suggestions? ^^Thank you so much! :)
推荐答案
以下是使用 foldRight
的解决方案:
Here is a solution using foldRight
:
val oldList = List(1, 2, 3, 7, 8, 10, 13, 14)
val newList = oldList.foldRight[List[List[Int]]](Nil)((a, b) => b match {
case (bh @ bhh :: _) :: bt if (bhh - a == 1) => (a :: bh) :: bt
case _ => (a :: Nil) :: b
})
因此,我们向后迭代条目,然后添加到现有的头列表中,或者根据区别是否为一个来添加新的头列表:
So we iterate the entries backwards and either prepend to the existing head list or add a new head list depending on whether the difference is one:
Nil
(14, ...) => (14 :: Nil) :: Nil
(13, ...) => (13 :: 14 :: Nil) :: Nil
(10, ...) => (10 :: Nil) :: (13 :: 14 :: Nil) :: Nil
...
我已经有一段时间没有使用Scala了,所以这可能不是最好的解决方案,但我希望您能理解。
I haven't used Scala for a while so this might not be the best solution, but I hope you get the idea.
这篇关于Scala提取列表中相差1(整数)的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!