Skip to content

Instantly share code, notes, and snippets.

@ajozwik
Last active January 4, 2016 03:49
Show Gist options
  • Save ajozwik/8564437 to your computer and use it in GitHub Desktop.
Save ajozwik/8564437 to your computer and use it in GitHub Desktop.
object S99_P26 {
def combinations[T](count: Int, ts: Seq[T]): Seq[Seq[T]] = {
def addHeadToSeqs[T](tss: Seq[Seq[T]], elt: T): Seq[Seq[T]] =
tss.map(ts => elt +: ts)
ts match {
case h +: tail if count == 1 =>
ts.flatMap(e => Seq(Seq(e)))
case h +: tail =>
combinations(count, tail) ++ addHeadToSeqs(combinations(count - 1, tail), h)
case _ => Nil
}
}
}
@rpietruc
Copy link

rpietruc commented Oct 6, 2014

Thank you for nice solution, I've made a simplified version.

object S99_P26 {
def combinations[T](count: Int, ts: Seq[T]): Seq[Seq[T]] = {
    if (count == 1)
        ts.map(Seq(_))

    else ts match {
        case h +: tail => combinations(count - 1, tail).map(h +: _) ++ combinations(count, tail)
        case _ => Nil
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment