C# String permutation

后端 未结 6 858
一个人的身影
一个人的身影 2020-12-11 07:27

I have 5 strings, such as: \"one\", \"two\", \"three\", \"four\", and \"five\". I need to get all permutations of these strings. I\'ve explored all internet resources, but a

6条回答
  •  醉酒成梦
    2020-12-11 08:28

    Here's a class that works in .Net 2.0. First, sort your array. Then use it by looping over while(Permute.Next(array)). When there are no more permutations, Permute.Next returns false.

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    public class Permute
    {
        public static bool Next(IList list)
        {
            int k = FindSmallestK(list);
            if (k < 0) return false;
            int l = FindLargestL(list, k);
            Swap(list, k, l);
            Reverse(list, k + 1);
            return true;
        }
    
        private static void Reverse(IList list, int p)
        {
            for (int i = p, j = list.Count - 1; i < j; i++, j--)
            {
                Swap(list, i, j);
            }
        }
    
        private static void Swap(IList list, int k, int l)
        {
            IComparable temp = list[k];
            list[k] = list[l];
            list[l] = temp;
        }
    
        private static int FindLargestL(IList list, int k)
        {
            for (int i = list.Count - 1; i > k; i--)
            {
                if (list[k].CompareTo(list[i]) < 0) return i;
            }
            return -1;
        }
    
        private static int FindSmallestK(IList list)
        {
            for (int i = 0; i < list.Count - 1; i++)
            {
                if (list[i].CompareTo(list[i + 1]) < 0) return i;
            }
            return -1;
        }
    }
    

提交回复
热议问题