简体   繁体   中英

C# Combination Filters

I have following code generating all possible combinations of a set of numbers.

enter image description here

This code generating combinations as follows {1 2 3 4 5 6}, {1 2 3 4 5 7}, {1 2 3 4 5 8}.....etc

But i need to apply some particular filters.

For example in any combination first digit should be "Even number", 2nd digit should be "ODD" etc.

I want to apply filter for all 6 digits in a combination. Could any one help. Thanks.


I suppose you don't have access to the source of Combinatorics.Combinations method. So you can only make filters in your foreach

Something like:

foreach (int[] combination in Combinatorics.Combinations(values, 6))
{
    // first filter
    if (combinations[0] % 2 == 0) // first digit should be even
    {
        // only now should the check be continued (second filter)
        if (combinations[1] % 2 != 0) // ... odd
        {
            // and so on...
            if (combinations[2] == someFilter)
            {
                // you should nest the "ifs" until "combinations[5]" and only
                // in the most inner "if" should the number be shown:
                string combination = string.format("{{0} {1} {2} {3} {4} {5}}", combinations[0], combinations[1], combinations[2], combinations[3], combinations[4], combinations[5]);
                Console.WriteLine(combination);
            }
        }
    }
}

您可以使用Where过滤结果

Combinatorics.Combinations(values, 6).Where(c => c.First() % 2 == 0 /* && ..other conditions */)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM