c函数,不允许c99,实现将大小为mustPass_num的一维数组mustPass[mustPass_num]的全排列用二维数组arrays[factorial(mustPass_num)][mustPass_num]输出。不允许c99
时间: 2023-06-19 10:05:55 浏览: 105
以下是一个实现将大小为mustPass_num的一维数组mustPass[mustPass_num]的全排列用二维数组arrays[factorial(mustPass_num)][mustPass_num]输出的c函数,它不允许c99:
```
#include <stdio.h>
int factorial(int n) {
int result = 1;
while (n > 1) {
result *= n--;
}
return result;
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void permute(int *mustPass, int mustPass_num, int **arrays, int *index) {
if (mustPass_num == 1) {
for (int i = 0; i < mustPass_num; i++) {
arrays[*index][i] = mustPass[i];
}
(*index)++;
return;
}
for (int i = 0; i < mustPass_num; i++) {
swap(&mustPass[i], &mustPass[mustPass_num - 1]);
permute(mustPass, mustPass_num - 1, arrays, index);
swap(&mustPass[i], &mustPass[mustPass_num - 1]);
}
}
void printArrays(int **arrays, int count, int size) {
for (int i = 0; i < count; i++) {
for (int j = 0; j < size; j++) {
printf("%d ", arrays[i][j]);
}
printf("\n");
}
}
void permuteArrays(int *mustPass, int mustPass_num, int **arrays) {
int count = factorial(mustPass_num);
int index = 0;
permute(mustPass, mustPass_num, arrays, &index);
printArrays(arrays, count, mustPass_num);
}
int main() {
int mustPass[] = {1, 2, 3};
int mustPass_num = sizeof(mustPass) / sizeof(int);
int **arrays = (int **)malloc(factorial(mustPass_num) * sizeof(int *));
for (int i = 0; i < factorial(mustPass_num); i++) {
arrays[i] = (int *)malloc(mustPass_num * sizeof(int));
}
permuteArrays(mustPass, mustPass_num, arrays);
for (int i = 0; i < factorial(mustPass_num); i++) {
free(arrays[i]);
}
free(arrays);
return 0;
}
```
这个函数首先计算出数组的全排列的数量,然后创建一个二维数组来存储这些排列。它使用递归来生成数组的所有排列,并将它们存储在二维数组中。最后,它打印出所有排列。
阅读全文