I am trying to write a C# function that, given an argument like new int[] { 2, 3, 2 } which specifies the upper bound + 1 for each element, would return the following (via IEnumberable<int[]>):
0 0 0
0 0 1
0 1 0
0 2 0
1 0 0
0 1 1
0 2 1
1 0 1
1 1 0
1 2 0
1 1 1
1 2 1
Note that the order is important: all the permutations with 0 non-zero elements, followed by all those with 1 non-zero elements, etc. Within one of those groups the order doesn’t matter.
I realize that these may not technically be permutations, but it’s the closest term that I know of. Also I realize that one way would be to return all the permutations in some order and then sort them according to a function that counts how many non-zero elements there are, but I am hoping for something more elegant and efficient.
I wanted an answer that doesn’t calculate everything first and then sort, while still only going through things the minimal amount of times. Here’s what I’ve got. Note that externally modifying the
int[]could screw up the results (alternately, could return anew int[]).The first method tells the helper method how many 0’s it wants in the output. The helper then calculates the results, stopping if it can’t fill in enough 0’s or if it runs through all the data.