c# - Finding all combinations, pseudo -
i have 10 rows, each row can have 1-10 numbers value of 1-100 (the actual value doesn't matter). example, first 3 rows like:
1. (2 numbers) 1st 2nd 1st 2nd 2. (1 number) combinations ---> 1st 1st 1st 1st 3. (2 numbers) 1st 1st 2nd 2nd
with real numbers:
1. 5, 7 5 7 5 7 2. 2 combinations ---> 2 2 2 2 3. 12, 24 12 12 24 24 results in total of 4 unique combinations.
how can solved? i've tried for-loops , if statements, won't work should.
eric lippert wrote fantastic article on how write method can take number of sequences, each of arbitrary size, , find cartesian product (that's technical term you're asking for) of of sequences in c# .
the code derives @ end of article follows, although highly suggest reading article see how ended there:
static ienumerable<ienumerable<t>> cartesianproduct<t>(this ienumerable<ienumerable<t>> sequences) { ienumerable<ienumerable<t>> emptyproduct = new[] { enumerable.empty<t>() }; return sequences.aggregate( emptyproduct, (accumulator, sequence) => accseq in accumulator item in sequence select accseq.concat(new[] {item})); }
simple example usage:
var array = new string[][] { new[] { "a", "b" }, new[] { "1", "2" } }; foreach (var product in array.cartesianproduct()) console.writeline(string.join(" ", product));
Comments
Post a Comment