permute.cpp

来自「经典c++程序的实现」· C++ 代码 · 共 47 行

CPP
47
字号
#include <iostream.h>
#include <stdlib.h>

#include "..\include\book.h"

typedef int ELEM;
#include "..\include\swap.h"

void permute(int *array, int n) {
  for (int i=n; i>0; i--)
    swap(array[i-1], array[Random(i)]);
}

int main(int argc, char** argv) {
  ELEM* A; // The array
  int n;
  int i;

  if(argc != 2) {
    cout << "Usage: permute <size_of_permutation>\n";
    exit(-1);
  }

  n = atoi(argv[1]);
  if ((A = (ELEM *)calloc(n, sizeof(ELEM))) == NULL) {
    cout << "Error: Unable to allocate space for permutation array\n";
    exit(-1);
  }

  for (i=0; i<n; i++)
    A[i] = i;

  Randomize();

  permute(A, n);

  for (i=0; i<n; i++) {
    cout << A[i];
    if (!((i+1)%10))
      cout << "\n";
    else
      cout << "  ";
  }
 cout << "\n";
 return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?