Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All permutations of a list [duplicate]

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.


like image 418
Kelly Elton Avatar asked Mar 01 '13 03:03

Kelly Elton


1 Answers

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++;
        }
    }
}
like image 182
Jesse C. Slicer Avatar answered Oct 05 '22 00:10

Jesse C. Slicer