I'd like to be able to take a list like this
var list=new List<int>{0, 1, 2};
And get a result like this
var result=
new List<List<int>>{
new List<int>{0, 1, 2},
new List<int>{0, 2, 1},
new List<int>{1, 0, 2},
new List<int>{1, 2, 0},
new List<int>{2, 0, 1},
new List<int>{2, 1, 0}
};
I'm not interested in sets with missing numbers, just combinations of the numbers that exist. Any ideas?
Also, I've looked into solutions like Getting all possible combinations from a list of numbers already, and they don't fit.
That one gives me something like this
var result=
new List<List<int>> {
// [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
// serialized the result to JSON so it would be quicker.
};
And it doesn't spit out all of the combinations.
Try these extension methods on for size:
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> sequence)
{
if (sequence == null)
{
yield break;
}
var list = sequence.ToList();
if (!list.Any())
{
yield return Enumerable.Empty<T>();
}
else
{
var startingElementIndex = 0;
foreach (var startingElement in list)
{
var index = startingElementIndex;
var remainingItems = list.Where((e, i) => i != index);
foreach (var permutationOfRemainder in remainingItems.Permute())
{
yield return permutationOfRemainder.Prepend(startingElement);
}
startingElementIndex++;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With