Skip to content

Instantly share code, notes, and snippets.

@jdegoes
Created April 13, 2014 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdegoes/10606628 to your computer and use it in GitHub Desktop.
Save jdegoes/10606628 to your computer and use it in GitHub Desktop.
N choose K in Scala
case class Choice[A](chosen: List[A], unchosen: List[A])
def nChoose1[A](n: List[A]): Stream[Choice[A]] = n match {
case Nil => Stream.empty[Choice[A]]
case head :: tail => Choice(head :: Nil, tail) #:: nChoose1(tail).map(choice => choice.copy(unchosen = head :: choice.unchosen))
}
def nChooseK[A](n: List[A], k: Int): Stream[Choice[A]] = {
if (k <= 0) Stream.empty[Choice[A]]
else if (k == 1) nChoose1(n)
else {
val rec = nChooseK(n, k - 1)
rec.flatMap { kminus1 =>
nChoose1(kminus1.unchosen).map(one => kminus1.copy(chosen = kminus1.chosen ++ one.chosen, unchosen = kminus1.unchosen -- one.chosen))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment