使用scala从列表中查找总和为给定值的四个元素

问题描述 投票:1回答:1

我是scala编程语言的新手,想要实现具有以下场景的代码。给定n个整数和整数样本三的列表样本,样本中有元素a,b,c和d,使得a + b + c + d = samplethree。在列表中找到所有唯一的四元组,它给出了样本三的总和

例:

sampleone =[1,0,-1,0,-2,2] and samplethree = 0 
a solution set is 
[-1,0,0,1]
[-2,-1,1,2]
[-2,0,0,2]

我用过的代码是

scala> def findFourElements(A: List[Int], n: Int, x: Int) = {
     | {
     | for(a <- 0 to A.length-3)
     | {
     | for(b <- a+1 to A.length-2)
     | {
     | for(c <- b+1 to A.length-1)
     | {
     |  for(d <- c+1 to A.length)
     | {
     | if(A(a) + A(b) + A(c) + A(d) == x)
     | {
     | print(A(a)+A(b)+A(c)+A(d))
     | }}}}}}
     | }
findFourElements: (A: List[Int], n: Int, x: Int)Unit


scala> val sampleone = List(1,0,-1,0,-2,2)
sampleone: List[Int] = List(1, 0, -1, 0, -2, 2)

scala> val sampletwo = sampleone.length
sampletwo: Int = 6

scala> val samplethree = 0
samplethree: Int = 0

scala> findFourElements(sampleone,sampletwo,samplethree)
0java.lang.IndexOutOfBoundsException: 6
  at scala.collection.LinearSeqOptimized$class.apply(LinearSeqOptimized.scala:65)
  at scala.collection.immutable.List.apply(List.scala:84)
  at $anonfun$findFourElements$1$$anonfun$apply$mcVI$sp$1$$anonfun$apply$mcVI$sp$2$$anonfun$apply$mcVI$sp$3.apply$mcVI$sp(<console>:33)
  at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160)
  at $anonfun$findFourElements$1$$anonfun$apply$mcVI$sp$1$$anonfun$apply$mcVI$sp$2.apply$mcVI$sp(<console>:31)
  at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160)
  at $anonfun$findFourElements$1$$anonfun$apply$mcVI$sp$1.apply$mcVI$sp(<console>:29)
  at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160)
  at $anonfun$findFourElements$1.apply$mcVI$sp(<console>:27)
  at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160)
  at findFourElements(<console>:25)
  ... 48 elided

但我收到索引超出绑定异常的错误。还有一种方法可以在scala中使用更优化的代码。

感谢帮助。

scala list functional-programming
1个回答
4
投票

这可能会做你想要的:

sampleone.combinations(4).filter(_.sum == samplethree)

combinations方法提供了一个迭代器,它依次提供每个可能的值组合。如果构造相同序列的方法不止一种,则只返回一个。

filter调用删除任何不总和为samplethree值的序列。

© www.soinside.com 2019 - 2024. All rights reserved.