say I have a set of numbers \'0\', \'1\', \'2\', ..., \'9\'. I want to find all numbers that contain exactly one of each of the numbers in my set.
The problem is: Be
Here is my C# 3.0 implementation of permutations you can find useful
public static class PermutationExpressions
{
public static IEnumerable> Permutations(this IEnumerable list)
{
return list.Permutations((uint)list.Count());
}
public static IEnumerable> Permutations(this IList list)
{
return list.Permutations((uint)list.Count);
}
private static IEnumerable> Permutations(this IEnumerable list, uint n)
{
if (n < 2) yield return list;
else
{
var ie = list.GetEnumerator();
for (var i = 0; i < n; i++)
{
ie.MoveNext();
var item = ie.Current;
var i1 = i;
var sub_list = list.Where((excluded, j) => j != i1).ToList();
var sub_permutations = sub_list.Permutations(n - 1);
foreach (var sub_permutation in sub_permutations)
{
yield return
Enumerable.Repeat(item, 1)
.Concat(sub_permutation);
}
}
}
}
}
[TestFixture]
public class TestPermutations
{
[Test]
public void Permutation_Returns_Permutations()
{
var permutations = PermutationExpressions.Permutations(new[] { "a", "b", "c" }.AsEnumerable());
foreach (var permutation in permutations)
{
Console.WriteLine(string.Join("", permutation.ToArray()));
}
Assert.AreEqual("abc_acb_bac_bca_cab_cba", permutations.Select(perm => perm.joinToString("")).joinToString("_"));
}
}