That taks turned to be awesome on so many levels.
I present you a pure LINQ (but not very efficient) solution.
static class Program
{
static void Main(string[] args)
{
var res = "cat".Anagrams();
foreach (var anagram in res)
Console.WriteLine(anagram.MergeToStr());
}
static IEnumerable> Anagrams(this IEnumerable collection) where T: IComparable
{
var total = collection.Count();
// provided str "cat" get all subsets c, a, ca, at, etc (really nonefficient)
var subsets = collection.Permutations()
.SelectMany(c => Enumerable.Range(1, total).Select(i => c.Take(i)))
.Distinct(new CollectionComparer());
return subsets;
}
public static IEnumerable> Permutations(this IEnumerable collection)
{
return collection.Count() > 1
?
from ch in collection
let set = new[] { ch }
from permutation in collection.Except(set).Permutations()
select set.Union(permutation)
:
new[] { collection };
}
public static string MergeToStr(this IEnumerable chars)
{
return new string(chars.ToArray());
}
}// class
// cause Distinct implementation is shit
public class CollectionComparer : IEqualityComparer> where T: IComparable
{
Dictionary, int> dict = new Dictionary, int>();
public bool Equals(IEnumerable x, IEnumerable y)
{
if (x.Count() != y.Count())
return false;
return x.Zip(y, (xi, yi) => xi.Equals(yi)).All(compareResult => compareResult);
}
public int GetHashCode(IEnumerable obj)
{
var inDict = dict.Keys.FirstOrDefault(k => Equals(k, obj));
if (inDict != null)
return dict[inDict];
else
{
int n = dict.Count;
dict[obj] = n;
return n;
}
}
}// class