GetCountOfAnagrams.cs

CSharp · Console

/Program.cs

using System;
using System.Linq;
					
public class Program
{
	public static double Factorial(int number)
	{
		return number == 1 ? 1 : number * Factorial(number - 1);
	}
	
	public static int GetCountOfAnagrams(string str)
	{
		if (string.IsNullOrEmpty(str))
		{
			return 0;
		}
		
		int length = str.Length;
		
		// отсортируем нашу строку
		string sortedStr = string.Concat(str.OrderBy(x => x));
		int count = 1;
		double res = Factorial(length);
		
		for (int i = 0; i < length - 1; i++)
		{
			// считаем одинаковые буквы в строке (множество с идентичными элементами)
			if (sortedStr[i] == sortedStr[i + 1])
			{
				count++;
			}
			else
			{
				res /= Factorial(count);
				count = 1;
			}
		}
		
		res /= Factorial(count);
		return (int)res;
	}
	
	public static void Main()
	{
		Console.WriteLine("UniLecs");
		Console.WriteLine(string.Format("Answer = {0}", GetCountOfAnagrams("SOLO")));
		Console.WriteLine(string.Format("Answer = {0}", GetCountOfAnagrams("ABCDDD")));   
	}
}
;