Are you aware that regular permutations don't do duplicates? Your data set of 9,1,3,9 will generate 16 permutations from an actual possible 24. If that's indeed what you're expecting, your permutation code can be just 14 lines of code (accounting for proper code formatting techniques). Further, you can put the results into a
HashSet
to avoid duplicate checking (although, even that isn't really necessary).
Here's some code I found with google:
public static class ExtensionMethods
{
public static IEnumerable<T[]> Permute<T>(this T[] xs, params T[] pre)
{
if (xs.Length == 0)
{
yield return pre;
}
for (int i = 0; i < xs.Length; i++)
{
foreach (T[] y in Permute(xs.Take(i).Union(xs.Skip(i+1)).ToArray(), pre.Union(new[] { xs[i] }).ToArray()))
{
yield return y;
}
}
}
}
And here's how to use it:
int[] values = {9,1,3,9};
HashSet<int[]> permutations = new HashSet<int[]>();
foreach(int[] perm in values.Permute())
{
permutations.Add(perm);
}
This will yield 16 permutations. If you change the last digit to an 8, you'll get 24 permutations.