def solve (xs: Seq[Int], target: Int): Option[(Int, Int)] = { val indexed = xs zip (0 until xs.size) @tailrec def solveRec (xs: Seq[(Int, Int)]): Option[(Int, Int)] = xs match { case Nil => None case (x, i) :: rest => rest find { case (y, j) => x + y == target } match { case None => solveRec(rest) case Some((y, j)) => Some((i, j)) } } solveRec(indexed) }
And the tests
class PairsumTest extends FunSuite { test("solve") { assert(solve(List(1234,5678,9012), 14690) == Some((1, 2))) assert(solve(List(1,2,3), 4) == Some((0, 2))) assert(solve(List(2,2,3), 4) == Some((0, 1))) assert(solve(List(5,10,15,20,25,30), 50) == Some((3, 5))) assert(solve(List(), 23) == None) assert(solve(List(5, 14, 38), 23) == None) } }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Scala
And the tests