Finds all of the permutations for the given Elements of type T. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Finds all of the permutations for the given Elements of type T.

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from w w  w  .j  a  v a2s  . co m*/

public class Main{
        private static List<List<T>> GetPermuations<T>(List<T> currentPermutation, IEnumerable<T> elementsToPermutate, int currentDepth, int numberOfElementsInPermutations)
        {
            var permutations = new List<List<T>>();
            foreach (var element in elementsToPermutate)
            {
                var permutationList = new List<T>(currentPermutation) { element };

                if (currentDepth + 1 < numberOfElementsInPermutations)
                {
                    permutations.AddRange(GetPermuations<T>(currentPermutation: permutationList,
                                                                   elementsToPermutate: elementsToPermutate,
                                                                   currentDepth: currentDepth + 1,
                                                                   numberOfElementsInPermutations:
                                                                       numberOfElementsInPermutations));
                }
                else
                {
                    permutations.Add(permutationList);
                }
            }

            return permutations;
        }
        /// <summary>
        /// Finds all of the permutations for the given Elements of type T.
        /// Each permutation will have a "numberOfElementsInPermutations" number of elements.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="elementsToPermutate"></param>
        /// <param name="numberOfElementsInPermutations"></param>
        /// <returns></returns>
        public static List<List<T>> GetPermuations<T>(IEnumerable<T> elementsToPermutate, int numberOfElementsInPermutations)
        {
            return GetPermuations(currentPermutation: new List<T>(), elementsToPermutate: elementsToPermutate,
                                  currentDepth: 0, numberOfElementsInPermutations: numberOfElementsInPermutations);
        }
}

Related Tutorials