Как я могу написать функцию, возвращающую все анаграммы данного слова (включая само слово) в любом порядке.
An anagram is a word formed from another by rearranging its letters, using all the original letters exactly once; for example, orchestra can be rearranged into carthorse. Write a function which returns all anagrams of a given word (including the word itself) in any order. For example GetAllAnagrams("abba") should return collection containing "aabb", "abab", "abba", "baab", "baba", "bbaa". using System; using System.Text; using System.Collections.Generic; public class AllAnagrams { public static ICollection<string> GetAllAnagrams(string str) { throw new NotImplementedException("Waiting to be implemented."); } public static void Main(string[] args) { ICollection<string> anagrams = GetAllAnagrams("abba"); foreach (string a in anagrams) Console.WriteLine(a); } }
Что я уже пробовал:
using System; using System.Collections.Generic; public class AllAnagrams { public static ICollection<string> GetAllAnagrams(string str) { List<string> _List = new List<string>(); bool[] noswitch = new bool[str.Length]; getOptions(str, ref noswitch, ref _List, str.Length); ICollection<string> list = _List; return list; } public void getOptions(string word, ref bool[] noswitch, ref List<string> options, int size) { if (size > 2) { for (int i = 0; i < noswitch.Length; i++) { noswitch[i] = true; getOptions(word, ref noswitch, size - 1); noswitch[i] = false; } } else { for (int y = 0; y < noswitch.Length; y++) { int prevCount = -1; if (noswitch[y] == false) { if (prevCount == -1) { prevCount = y; } else { char[] array = word.ToCharArray(); char charb = word[y]; array[y] = array[prevCount]; array[prevCount] = charb; string newWord = new string (array); if (!options.Contains(newWord)) { options.Add(newWord); Console.WriteLine("added"); } } } } } } public static void Main(string[] args) { ICollection<string> anagrams = GetAllAnagrams("abba"); foreach (string a in anagrams) Console.WriteLine(a); } }