Skip to content

Instantly share code, notes, and snippets.

@sachintha81
Created January 13, 2017 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachintha81/f906bcb3f067e5db33517b9eb1655abd to your computer and use it in GitHub Desktop.
Save sachintha81/f906bcb3f067e5db33517b9eb1655abd to your computer and use it in GitHub Desktop.
All Possible Combinations of a list of Values
namespace Combinations
{
public class Combinations
{
public static void Main(string[] args)
{
GetCombination(new List<int> { 1, 2, 3 });
}
public static void GetCombination(List<int> list)
{
double count = Math.Pow(2, list.Count);
for (int i = 1; i <= count - 1; i++)
{
string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
for (int j = 0; j < str.Length; j++)
{
if (str[j] == '1')
{
Console.Write(list[j]);
}
}
Console.WriteLine();
}
}
}
}
@sachintha81
Copy link
Author

sachintha81 commented Jan 13, 2017

PROBLEM STATEMENT

I have a list of integers in my C# program. However, I know the number of items I have in my list only at run-time.

Let us say, for the sake of simplicity, my list is {1, 2, 3}
Now I need to generate all possible combinations as follows.

{1, 2, 3} {1, 2} {1, 3} {2, 3} {1} {2} {3}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment