如何在不使用可变集合的情况下将 List(1,2,30,13,4)
转换为 List(1,2,3,4)
?
30是一种转义数字;如果找到,则应将其删除,并且下一个数字应减少 10。
最佳答案
您可能应该检查您的代码/用例,因为无论如何,这有点难闻:
List(1,2,30,13,4).foldLeft((List.empty[Int], false)) {
case ((accumulator, wasFound), next) =>
if(wasFound) (accumulator :+ (next - 10), false)
else if(next == 30) (accumulator, true)
else (accumulator :+ next, false)
}._1
基本上,您可以保留一个 bool 值和一个累加器,并用它来记住是否找到 30,并在找到时采取适当的操作。
请注意,如果您有类似 List(1,3,30,40)
的内容,这对您没有帮助,输出将为 List(1,3,30)
,你应该明确这种情况是否可接受,如果 Not Acceptable ,我将使用递归解决方案,该解决方案允许在元素为 30 的情况下迭代两次:
scala> def loop(list: List[Int], acc: List[Int], wasFound: Boolean, toRemove: Int): List[Int] = list match {
| case h :: t =>
| if(wasFound) loop((h - 10) :: t, acc, false, toRemove)
| else if(h == toRemove) loop(t, acc, true, toRemove)
| else loop(t, acc :+ h, false, toRemove)
| case Nil =>
| acc
| }
loop: (list: List[Int], acc: List[Int], wasFound: Boolean, toRemove: Int)List[Int]
scala> loop(List(1,2,30,13,4), List(), false, 30)
res1: List[Int] = List(1, 2, 3, 4)
scala> loop(List(1,2,30,40, 13,4), List(), false, 30)
res2: List[Int] = List(1, 2, 3, 4)
逻辑非常相似,唯一的区别是你迭代了 30 之后找到的那个,所以如果它是另一个 30,它就会被删除,下一个就会减少。
关于list - Scala 迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39450043/