1

I have a program, where I have to generate all R-digit numbers among N digits in C++, for example for N=3 (all digits from 1 to N inclusive) and R=2 the program should generate 12 13 21 23 31 32. I tried to do this with arrays as follows, but it does not seem to work correctly.

#define nmax 20
#include <iostream>
using namespace std;
int n, r;
void print(int[]);

int main()
{
    cin >> n;
    cin >> r;

    int a[nmax];
    int b[nmax];
    int used[nmax];

    for (int p = 1; p <= n; p++) {
        //Filling the a[] array with numbers from 1 to n
        a[p] = n;
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < r; j++) {
            b[j] = a[i];
            used[j] = 1;
            if (used[j]) {
                b[j] = a[i + 1];
            }
            used[j] = 0;
        }
        print(b);
    }

    return 0;
}

void print(int k[]) {
    for (int i = 0; i < r; i++) {
        cout << k[i];
    }
}
4

1 回答 1

0

如果我正确理解您的问题,您可以浏览这个网站,它解释了问题并彻底提出了解决方案。

这是一个稍微改动的代码:

请注意,对于较大的 N 值,时间是一个问题。

#define N    5   // number of elements to permute.  Let N > 2
#include <iostream>
using namespace std;

// NOTICE:  Original Copyright 1991-2010, Phillip Paul Fuchs

void PrintPerm(unsigned int *a, unsigned int j, unsigned int i){
   for(unsigned int x = 0; x < N; x++)
      cout << " " << a[x];
   cout << "    swapped( " << j << " , " << i << " )\n";
}

void QuickPerm(void){
   unsigned int a[N], p[N+1];
   register unsigned int i, j, PermCounter = 1; // Upper Index i; Lower Index j

   for(i = 0; i < N; i++){   // initialize arrays; a[N] can be any type
      a[i] = i + 1;   // a[i] value is not revealed and can be arbitrary
      p[i] = i;
   }
   p[N] = N; // p[N] > 0 controls iteration and the index boundary for i
   PrintPerm(a, 0, 0);   // remove comment to PrintPerm array a[]
   i = 1;   // setup first swap points to be 1 and 0 respectively (i & j)
   while(i < N){
      p[i]--;             // decrease index "weight" for i by one
      j = i % 2 * p[i];   // IF i is odd then j = p[i] otherwise j = 0
      swap(a[i], a[j]);   // swap(a[j], a[i])
      PrintPerm(a, j, i);   // remove comment to PrintPerm target array a[]
      PermCounter++;
      i = 1;              // reset index i to 1 (assumed)
      while (!p[i]) {      // while (p[i] == 0)
         p[i] = i;        // reset p[i] zero value
         i++;             // set new index value for i (increase by one)
      } // while(!p[i])
   } // while(i < N)
    cout << "\n\n ---> " << PermCounter << " permutations. \n\n\n";
} // QuickPerm()

int main(){
    QuickPerm();
} //main

这是原始代码中修改项目的列表。

  1. N 定义为 5 而不是 12。
  2. 添加了一个计数器以获得更多信息结果。
  3. 通过使用 c++ 标准库的swap()功能减少了原始交换指令。
  4. getch()被删除。
  5. “Display()”函数已重命名为“PrintPerm()”。
  6. printf()功能已被替换cout
  7. 添加了排列的打印数量。
于 2018-02-28T12:10:04.953 回答