Last active
August 29, 2015 14:01
-
-
Save DeepSky8/5840274421d3bc3fe917 to your computer and use it in GitHub Desktop.
Generate the combinations of K distinct objects chosen from the N elements of a list. In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficient). For pure mathematicians, this result may be great. But we want to really gene…
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
scala> combinations(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, h', i', j', k', l')) | |
res0: List[List[Symbol]] = List(List('a, 'b, 'c), List('a, 'b, 'd), List('a, 'b, 'e), ... | |
def combinations[A](size: Int, pool: List[A]): List[List[A]] = pool match { | |
case Nil => Nil | |
case h :: t => if(size <= 0) Nil else if (size == 1) { | |
list(h) :: combinations(size, t) | |
} else { | |
helper(h, combinations(size-1, t) | |
} | |
} | |
def helper[A](distribute: A, combs: List[List[A]]): List[List[A]] = combs match { | |
case Nil => Nil | |
case h :: t => (distribute :: h) :: helper (distribute, t) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment