permutation in c#

前端 未结 5 2143
无人共我
无人共我 2021-01-13 05:16

Is it possible to generate all permutations of a collection in c#?

char[] inputSet = { \'A\',\'B\',\'C\' };
Permutations permutations = new Permu         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-13 05:51

    I've already faced the problem and I wrote these simple methods:

        public static IList GeneratePermutations(T[] objs, long? limit)
        {
            var result = new List();
            long n = Factorial(objs.Length);
            n = (!limit.HasValue || limit.Value > n) ? n : (limit.Value);
    
            for (long k = 0; k < n; k++)
            {
                T[] kperm = GenerateKthPermutation(k, objs);
                result.Add(kperm);
            }
    
            return result;
        }
    
        public static T[] GenerateKthPermutation(long k, T[] objs)
        {
            T[] permutedObjs = new T[objs.Length];
    
            for (int i = 0; i < objs.Length; i++)
            {
                permutedObjs[i] = objs[i];
            }
            for (int j = 2; j < objs.Length + 1; j++)
            {
                k = k / (j - 1);                      // integer division cuts off the remainder
                long i1 = (k % j);
                long i2 = j - 1;
                if (i1 != i2)
                {
                    T tmpObj1 = permutedObjs[i1];
                    T tmpObj2 = permutedObjs[i2];
                    permutedObjs[i1] = tmpObj2;
                    permutedObjs[i2] = tmpObj1;
                }
            }
            return permutedObjs;
        }
    
        public static long Factorial(int n)
        {
            if (n < 0) { throw new Exception("Unaccepted input for factorial"); }    //error result - undefined
            if (n > 256) { throw new Exception("Input too big for factorial"); }  //error result - input is too big
    
            if (n == 0) { return 1; }
    
            // Calculate the factorial iteratively rather than recursively:
    
            long tempResult = 1;
            for (int i = 1; i <= n; i++)
            {
                tempResult *= i;
            }
            return tempResult;
        }
    

    Usage:

    var perms = Utilities.GeneratePermutations(new char[]{'A','B','C'}, null);
    

提交回复
热议问题