c# - How to generate all subsets of a given size? -
given number n, , subset size, want possible subsets of specified size of set {1, ..., n}.
expected result for n = 5
, subsetsize = 4
:
{{1,2,3,4}, {1,2,3,5}, {1,3,4,5}, {1,2,4,5}, {2,3,4,5}}
(that list<list<int>>
)
that means need (subsetsize choose n) subsets (newton's symbol).
any idea algorithm find me such list of lists of integers? i'm implementing in c#, if matters.
internal class program { private static ienumerable<ienumerable<int>> subsets(int n, int subsetsize) { ienumerable<int> sequence = enumerable.range(1, n); // generate list of sequences containing 1 element e.g. {1}, {2}, ... var oneelemsequences = sequence.select(x => new[] { x }).tolist(); // generate list of int sequences var result = new list<list<int>>(); // add initial empty set result.add(new list<int>()); // generate powerset, skip sequences long foreach (var oneelemsequence in oneelemsequences) { int length = result.count; (int = 0; < length; i++) { if (result[i].count >= subsetsize) continue; result.add(result[i].concat(oneelemsequence).tolist()); } } return result.where(x => x.count == subsetsize); } private static void outputsubset(int n, ienumerable<ienumerable<int>> subsets) { console.writeline("n: {0}", n); foreach (var subset in subsets) { console.writeline("\t{0}", string.join(" ", subset.select(x => x.tostring()))); } } private static void main() { (int n = 1; n < 500; n++) { var subsets = subsets(n, subsetsize: 4); outputsubset(n, subsets); } } }
output:
n: 1 n: 2 n: 3 n: 4 1 2 3 4 n: 5 1 2 3 4 1 2 3 5 1 2 4 5 1 3 4 5 2 3 4 5 n: 6 1 2 3 4 1 2 3 5 1 2 4 5 1 3 4 5 2 3 4 5 1 2 3 6 1 2 4 6 1 3 4 6 2 3 4 6 1 2 5 6 1 3 5 6 2 3 5 6 1 4 5 6 2 4 5 6 3 4 5 6 n: 7 1 2 3 4 1 2 3 5 1 2 4 5 1 3 4 5 2 3 4 5 1 2 3 6 ...
Comments
Post a Comment