【发布时间】:2020-06-20 15:51:22
【问题描述】:
这是一个试图找出数组{10, 11, 12, 13}的所有紊乱的程序
但它不起作用,因为当涉及到 depth==0, i==0 和 Peano[]=={0, 1, 2, 3} 时,for 循环没有结束,然后 i 递减为 -1。这是怎么回事?
#include<stdio.h>
#include<stdlib.h>
unsigned long long derange(int *array, int LEN, _Bool display, int *Peano, unsigned depth);
int main(void){
int i ,LEN=4, *Peano=malloc(sizeof(int));
int array[4]={10,11,12,13};
for(i=0; i<LEN; i++)Peano[i]=i;
derange(array, LEN, 1, Peano, 0);
printf("this derangement of the array total of %llu.\n", derange(array, LEN, 0, Peano, 0));
return 0;}
unsigned long long derange(int *array, int LEN, _Bool display, int *Peano, unsigned depth){
int i, temp;
unsigned long long count=0;
if(depth==LEN){
if(display){
for(i=0; i<LEN; i++)
fprintf(stdout, "%d\040", array[i]);
putchar('\n');}
return 1;}
for(i=LEN-1; i>=depth; i--){
if(i==Peano[depth])continue;
temp=Peano[i]; Peano[i]=Peano[depth]; Peano[depth]=temp;
temp=array[i]; array[i]=array[depth]; array[depth]=temp;
count += derange(array, LEN, display, Peano, depth+1);
temp=Peano[i]; Peano[i]=Peano[depth]; Peano[depth]=temp;
temp=array[i]; array[i]=array[depth]; array[depth]=temp;}
return count;}
【问题讨论】:
-
请清理您的代码展示。分配
Peano有什么意义?您希望它是一个由 4 个(或LEN)整数组成的数组,但您只为一个整数分配存储空间。为什么不使用int Peano[LEN]?
标签: c algorithm permutation