Home > Blockchain >  How to write all possible combinations
How to write all possible combinations

Time:11-26

For a better understanding, I'll give you a simple example: We have 10 lamps. We can light one or two. It is necessary to write down all the ways to light the two lamps. This example is simple. And we can just list all the options like this:

List<string> lstAllOptions = new List<string> ( );

            for ( int i = 1; i <= 10; i   )
            {
                lstAllOptions.Add ( i.ToString ( ) );
            }

            for ( int i = 1; i <= 10; i   )
            {
                for ( int j = 1; j <= 10; j   )
                {
                    if ( i != j && j>i )
                    {
                        lstAllOptions.Add ( i.ToString ( )   " and "   j.ToString ( ) );
                    }
                }
            }

But what if the user sets the number of lamps? We can have 43 lamps and the ability to turn on 19 of them. Or as much as you like. I can increase the number of For, but it is very difficult. How to solve this problem easier and make a universal method for any number of lamps?

CodePudding user response:

Here's how you can compute such a combination:

public static IEnumerable<IEnumerable<int>> AllCombinations(int n, int k) =>
    from i in Enumerable.Range(0, 1 << n)
    let r = Enumerable.Range(0, n).Select(j => ((i & 1 << j) == 0 ? 1 : 0))
    where r.Count(s => s == 1) <= k
    select r;

However, with n == 43 it blows pat what an integer can hold.

It does work for lower values:

Console.WriteLine(AllCombinations(24, 19).Count());

Gives:

16764265
  • Related