Skip to content

Instantly share code, notes, and snippets.

@Slakah
Created December 1, 2020 13:07
Show Gist options
  • Save Slakah/bf70818dc5be3093d3e01753ee4676b7 to your computer and use it in GitHub Desktop.
Save Slakah/bf70818dc5be3093d3e01753ee4676b7 to your computer and use it in GitHub Desktop.
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