Created
April 13, 2014 23:34
-
-
Save jdegoes/10606628 to your computer and use it in GitHub Desktop.
N choose K in Scala
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
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