All Possible Combinations of a list of Values
try this:
static void Main(string[] args)
{
GetCombination(new List<int> { 1, 2, 3 });
}
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();
}
}
How to get all possible combinations of a list’s elements?
Have a look at itertools.combinations:
itertools.combinations(iterable, r)
Return r length subsequences of elements from
the input iterable.Combinations are emitted in lexicographic sort order. So, if the
input iterable is sorted, the
combination tuples will be produced in
sorted order.
Since 2.6, batteries are included!
All possible combinations of elements in a list which are next to each other
You can use a recursive generator function:
stuff = [1, 2, 3, 4]
def get_combos(d, c = []):
yield tuple(c)
if d:
yield from get_combos(d[1:], c+[d[0]])
yield from get_combos(d[1:], [d[0]])
result = set(filter(None, get_combos(stuff)))
Output:
{(1,),
(2,),
(3,),
(4,),
(1, 2),
(2, 3),
(3, 4),
(1, 2, 3),
(2, 3, 4),
(1, 2, 3, 4)}
Generate possible combination of values from a list
From the output you're giving, it seems you want the combinations and not the permutations.
You can iterate over all possible valid lengths (0 to 3) and create a sequence like that.
import itertools as it
list(it.chain.from_iterable(it.combinations([1, 2, 3], i) for i in range(4)))
will output:
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Related Topics
Temporarily Clear the Terminal in Linux
Detect Windows Version in .Net
Load an Exe File and Run It from Memory
Async/Await With/Without Awaiting (Fire and Forget)
Making a Property Deserialize But Not Serialize with JSON.Net
System.Unauthorizedaccessexception While Running .Exe Under Program Files
How to Use Global Variables in C#
How to I Catch Ssl Exceptions in a Mono Httplistener Server
How to Abort a Task Like Aborting a Thread (Thread.Abort Method)
Reading 64Bit Registry from a 32Bit Application
Design - Where Should Objects Be Registered When Using Windsor
Deserializing JSON into an Object
Differencebetween Nullable<T>.Hasvalue or Nullable<T> != Null