You can use such a recursive function - you do not need to print the result at the end, you can add it to the list, etc.
The function works starting from an empty line. At each step, you add one more character - in this case you add either 0 or 1 .
If 1 added, we will take this into account by decreasing the ones value on the next function call. (In a more general case, you can transfer a list of all the elements that you want to rearrange - then the process should select from this list, add it to your permutation and remove it from the list. Repeat this until the list is empty and you move all the elements to list.)
When the string reaches the desired length, we are done and we will return.
#include <stdio.h> void recurse(char *str, int length, int maxLength, int ones) { if (length == maxLength) { // we are finished printf("%s\n", str); return; } if (ones > 0) { // put a 1 into the new string str[length] = '1'; recurse(str, length + 1, maxLength, ones - 1); } if (ones < maxLength - length) { // there are still spaces for 0s // put a 0 into the string str[length] = '0'; recurse(str, length + 1, maxLength, ones); } } int main() { const int maxLength = 5; char buffer[maxLength + 1]; buffer[maxLength] = 0; int ones; for (ones = 0; ones <= maxLength; ones++) { printf("Ones: %i\n", ones); recurse(buffer, 0, maxLength, ones); printf("\n"); } return 0; }
The result is as follows:
Ones: 0 00000 Ones: 1 10000 01000 00100 00010 00001 Ones: 2 11000 10100 10010 10001 01100 01010 01001 00110 00101 00011 Ones: 3 11100 11010 11001 10110 10101 10011 01110 01101 01011 00111 Ones: 4 11110 11101 11011 10111 01111 Ones: 5 11111
Finally, if you really don't want / shouldn't learn / use C, I would recommend using C ++ because you get really nice features like std::vector and std::set , and so many other things that will make your life a lot easier, I would write this completely different in C ++.