I'd like to get all possible permutations of numbers in an array - n!/k! whereas n is the size of the array and k the number of identical numbers.
For example, there would be 3 (3!/2!) possible permutations of [3,0,0]:
- [3,0,0]
- [0,3,0]
- [0,0,3]
Another example would be [2,1,0], which would yield 6 (3!/1!) permutations:
- [2,1,0]
- [1,2,0]
- [0,1,2]
- [0,2,1]
- [2,0,1]
- [1,0,2]
I've been successfully using code from here:
static IEnumerable<IEnumerable<T>>
GetPermutationsWithRept<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutationsWithRept(list, length - 1)
.SelectMany(t => list,
(t1, t2) => t1.Concat(new T[] { t2 }));
}
After generating the permutations, I would run Sum()
to validate each permutation. This, however, might not be a efficient solution. Is there another way to achieve this?