迭代的解决方案,以频带排列计算C语言 [英] iterative solution to permutation calculation in C

查看:147
本文介绍了迭代的解决方案,以频带排列计算C语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理迭代问题。我应该传递两个整型成一个函数,从而重新present一批N个对象和M值,我必须找到的所有排列的。我也给出什么样的输出应该看起来像一个样本

I'm working on a problem dealing with iteration. I'm supposed to pass in two ints into a function, which represent a number of N objects and M values that I must find all permutations of. I am also given a sample of what the output is supposed to look like

无效perm_iter(INT N,INT nr_values​​) 并且输出这应该打印是:

void perm_iter(int N, int nr_values) and the output this is supposed to print is :

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 by using a swap function to change the orders of strings to find all permutations of a string, but I'm unsure of how to use iteration to get the same, or similar result. Is this a case where I need to use the stack and push/pop iteratively to get my answer? I was thinking I could use something like a set of nested loops to take the place of recursion and get something like this output but I'm unsure how to set the loops up to go through every permutation and not just iterate, missing some of the possible permutations.

任何帮助将是AP preciated,并感谢您的时间。

Any help would be appreciated, and thank you for your time.

推荐答案

您只需要计数每一个数字,直到最大达到,然后复位并增加了下。

You just need to count up each "digit" until the max is reached, then reset and increment the next.

想象nr_values​​是10(其中n = 2):

Imagine nr_values is 10 (with 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 

看起来很熟悉,因为它只是正规军计算在这种情况下。

Looks familiar because it's just "regular" counting in this case.

实现这个就像你计数:在每个步骤中,增加最左边的值。如果最大达到,复位和递增的下一个值等

Implement this just like you count up: In each step, increment the leftmost value. If max is reached, reset and increment the next value etc.

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);
}

这篇关于迭代的解决方案,以频带排列计算C语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆