Iterative solution for computing permutations in C

I am working on an iteration related issue. I have to pass two ints to a function, which is the number of N objects and M values ​​that all permutations should find. I am also given a sample of what the output should look like.

void perm_iter (int N, int nr_values) and the output to be printed is as follows:

Called : perm_iter(3, 2);

0  0  0
0  0  1
0  1  0
0  1  1
1  0  0
1  0  1
1  1  0
1  1  1

I understand the concept of recursion using the swap function to reorder strings to find all permutations of a string, but I'm not sure how to use iteration to get the same or similar result. Is this the case when I need to use the stack and push / pop iteratively to get an answer? I thought I could use something like a set of nested loops to replace recursion and get something like this output, but I'm not sure how to set up loops to go through each permutation, and not just iterations, possible permutations.

Any help would be appreciated and thanks for your time.

+4
source share
1 answer

, reset .

, nr_values ​​ 10 ( n = 2):

0 0
0 1 
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9 
1 0
1 1 
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9 

, "" .

, : . max , reset ..

void perm_iter(int n, int nr_values) {
  int[] counter = new int[n];
  int i;

  // Clear all values
  for (i = 0; i < n; i++) {
    counter[i] = 0;
  }

  do {
    // Print the current set of values
    for (i = 0; i < n; i++) {
      printf("%n ", counter[i]);
    }
    printf("\n");

    // Keep incrementing while the values overflow,
    // starting at the rightmost counter
    i = n - 1;
    while (i >= 0) {
      counter[i]++;
      if (counter[i] < nr_values) {
        break;
      } 
      counter[i] = 0;
      i--;
    }
    // We are done when the first value overflows
  } while (i >= 0);
}
+2

Source: https://habr.com/ru/post/1614069/


All Articles