Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all parameters combinations possible

I have a list of parameters with possible values :

// Definition of a parameter
public class prmMatrix
{
    public string Name { get; set; }
    public List<string> PossibleValues { get; set; }

    public prmMatrix(string name, List<string> values)
    {
        Name = name;
        PossibleValues = values;
    }
}

//[...]

// List of params       
List<prmMatrix> lstParams = new List<prmMatrix>();

lstParams.Add(new prmMatrix("Option A", new List<string>() { "Yes", "No" }));
lstParams.Add(new prmMatrix("Option B", new List<string>() { "Positive", "Negative" }));

I would like to have all the combinations of parameters possible, ex.:

[Option A:Yes][Option B:Positive]
[Option A:Yes][Option B:Negative]
[Option A:No][Option B:Positive]
[Option A:No][Option B:Negative]

What's the best way in C# ?

like image 791
Bruno Avatar asked Jan 19 '23 06:01

Bruno


1 Answers

This is pretty easy with recursion:

void ImplCombinations(List<prmMatrix> plist, string built, int depth, List<string> results)
{
    if (depth >= plist.Count()) {
        results.Add(built);
        return;
    }

    prmMatrix next = plist[depth];
    built += "[" + next.Name + ":";
    foreach (var option in next.PossibleValues)
        ImplCombinations(plist, built + option + "]", depth + 1, results);
}

List<string> GetCombinations(List<prmMatrix> plist)
{
    List<string> results = new List<string>();
    ImplCombinations(plist, "", 0, results);
    return results;
}
like image 84
Ben Voigt Avatar answered Jan 26 '23 01:01

Ben Voigt