Reputation: 23
I need to create a procedure that will allow me to get the full set of combinations of three repeated values uniquely for three or more groups.
For example I can have 3 groups (R1 - R2 - R3) and three values (A - AB - B) and I have to get all the possible combinations divided into 3 groups.
Like this:
Groups 1° 2° 3° 4° 5° .......
R1 A - A - AB - AB - AB ...
R2 A - A - A - A - BB ...
R3 A - AB - A - A - A ...
I have to be sure that all possible sequences are present and never repeated.
Unfortunately I'm new in the world of programming and I have no knowledge of combinatorics. I could not figure out how to handle it...
I apologize if I was unclear, and thank you in advance to anyone who can give me some help.
Upvotes: 2
Views: 481
Reputation: 4636
I think you want all combinations for your values....
Here is the generic way to do it in C#...
static IEnumerable<IEnumerable<T>> Combinations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return Combinations(list, length - 1)
.SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
}
And you call it like this...
var groups = new List<string>() { "R1", "R2", "R3" };
var values = new List<string>() { "AA", "AB", "BB" };
var combinations = Combinations(values, groups.Count);
var i = 0;
var stringFormat = string.Join(", ", groups.Select(x => x +"={"+ i++ +"}"));
// stringFormat looks like "R1={0}, R2={1}, R3={2}"
foreach (var value in combinations)
{
var arrayOfValues = value.ToArray(); // each value is a list of the combinations.
Console.WriteLine(string.Format(stringFormat, arrayOfValues));
}
You mentioned your inexperience so I've included doing it the hard coded way which is easier to follow...
var values = new List<string>() { "AA", "AB", "BB" };
foreach (var value1 in values)
{
foreach (var value2 in values)
{
foreach (var value3 in values)
{
Console.WriteLine(string.Format("R1 = {0}, R2 = {1}, R3 = {2}", value1, value2, value3));
}
}
}
With the output looking like so...
R1=AA, R2=AA, R3=AA
R1=AA, R2=AA, R3=AB
R1=AA, R2=AA, R3=BB
R1=AA, R2=AB, R3=AA
R1=AA, R2=AB, R3=AB
R1=AA, R2=AB, R3=BB
R1=AA, R2=BB, R3=AA
R1=AA, R2=BB, R3=AB
R1=AA, R2=BB, R3=BB
R1=AB, R2=AA, R3=AA
R1=AB, R2=AA, R3=AB
R1=AB, R2=AA, R3=BB
R1=AB, R2=AB, R3=AA
R1=AB, R2=AB, R3=AB
R1=AB, R2=AB, R3=BB
R1=AB, R2=BB, R3=AA
R1=AB, R2=BB, R3=AB
R1=AB, R2=BB, R3=BB
R1=BB, R2=AA, R3=AA
R1=BB, R2=AA, R3=AB
R1=BB, R2=AA, R3=BB
R1=BB, R2=AB, R3=AA
R1=BB, R2=AB, R3=AB
R1=BB, R2=AB, R3=BB
R1=BB, R2=BB, R3=AA
R1=BB, R2=BB, R3=AB
R1=BB, R2=BB, R3=BB
Upvotes: 1