(C#)計算字符串排列組合數 如"abcd"組合數爲24 "aabb"組合數爲6

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static long GetA(int m, int n)
        {
            long num = -1;
            if (m >= n && n >= 0 && m > 0)
            {
                num = 1;
                for (int i = 0; i < n; i++)
                {
                    num *= m - i;
                }
                return num;
            }
            return num;
        }

        public static long GetCombinationCount(string input)
        {
            long count;
            if (input == null)
                count = -1;
            else if (input == string.Empty)
                count = 0;
            else
            {
                int length = input.Length;
                if (length > 25)
                    count = -1;
                else
                {
                    Dictionary<char, int> dic = new Dictionary<char, int>();
                    foreach (char item in input)
                    {
                        if (!dic.ContainsKey(item))
                            dic.Add(item, 1);
                        else
                            dic[item]++;
                    }
                    count = GetA(length, length);
                    if (dic.Count != length)
                    {
                        Dictionary<char, int>.Enumerator enu = dic.GetEnumerator();
                        while (enu.MoveNext())
                        {
                            int tmp = enu.Current.Value;
                            if (tmp != 1)
                                count /= GetA(tmp, tmp);
                        }
                    }
                }

            }
            return count;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(GetA(50, 20));
            Console.WriteLine(GetA(50, 20) * 10);
            Console.WriteLine(GetCombinationCount("abcdefghijklmnopqrstuvwxy"));
            Console.WriteLine(GetCombinationCount("abcdefghijklmnopqrstuvwxyz"));
            Console.WriteLine(GetCombinationCount("1234567890"));
            Console.WriteLine(GetCombinationCount("1122333456"));
            Console.WriteLine(GetCombinationCount("1234567890") / GetA(2, 2) / GetA(2, 2) / GetA(3, 3));
        }
    }
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章