Created
December 1, 2020 13:07
-
-
Save Slakah/bf70818dc5be3093d3e01753ee4676b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import $ivy.`org.typelevel::cats-core:2.3.0` | |
def find2Addends(numbers: List[Long], sum: Long): Option[(Long, Long)] = { | |
numbers.collectFirstSome { x => | |
val y = sum - x | |
if (numbers.contains(y)) Some((x, y)) | |
else None | |
} | |
} | |
def findNAddends(numbers: List[Long], sum: Long, n: Long): Option[List[Long]] = { | |
n match { | |
case 2 => find2Addends(numbers, sum).map { case (x, y) => List(x, y) } | |
case _ => | |
def loop(l: List[Long]): Option[List[Long]] = { | |
l match { | |
case head :: rest => | |
findNAddends(rest, sum - head, n - 1) match { | |
case None => loop(rest) | |
case Some(addends) => Some(head :: addends) | |
} | |
case Nil => None | |
} | |
} | |
loop(numbers) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment