2017-03-25 1 views
0

나는 정렬 된 int 배열의 모든 순열을 나열한 다음 각 순열을 사용한다. 비록 함수가 의도 한대로 작동하지만 printf ("\ n")를 제거 할 때주의를 기울였습니다. 주에서는 프로그램이 작동하지만 멈추지 않습니다. 그것으로, 그것은 잘 작동합니다. 코드는 다음과 같습니다. 아무도 내가 무슨 일이 일어나고 있는지 이해할 수 있도록 도와 줄 수 있습니까?c 프로그램 코드가 새로운 줄을 인쇄하지 않고 루핑을 멈추지 않는다

#include <stdio.h> 
#include <stdlib.h> 
#define ARRAYSIZE 4 

int nextPermutation (int array[], int arraySize); 

int main() 
{ 
    int *array = calloc(ARRAYSIZE,sizeof(int)),i; 

    for(i=0; i<ARRAYSIZE; i++) 
    { 
     array[i]=i+1; 
    } 

    while(nextPermutation(array,ARRAYSIZE)) 
    { 

     for(i=0; i<ARRAYSIZE; i++) 
     { 
      printf("%d ",array[i]); 
     } 
     printf("\n"); 

    } 

    return 0; 
} 

int nextPermutation(int array[], int arraySize) 
{ 

    int maxElement=arraySize,i,maxElementIndex,inDecOrder; 

    //check to see if the array is in descending order 
    for(i=0; i<arraySize-1; i++) 
    { 
     if(array[i]<array[i+1]) 
     { 
      inDecOrder = 0; 
      break; 
     } 
    } 
    //if the array is in descending order then return 0 
    if(inDecOrder)return 0; 
    //find the index of the max element. 
    for(i=0; i<arraySize; i++) 
    { 
     if(array[i]==maxElement) 
     { 
      maxElementIndex = i; 
      break; 
     } 
    } 

    if(maxElementIndex!=0) 
    { 
     //if the max element is not in the first index then move it left and get next permutation 
     array[i]=array[i-1]; 
     array[i-1]=maxElement; 
     return 1; 

    } 
    else 
    { 
     //if the max index is in the first index then create an array without the max index 
     int *newArray = calloc(arraySize-1,sizeof(int)); 

     //copy the elements from the first array into the new array with out the max element and get next permutation 
     for(i=1; i<arraySize; i++) 
     { 
      newArray[i-1]=array[i]; 
     } 
     nextPermutation(newArray,arraySize-1); 
     for(i=0; i<arraySize-1; i++) 
     { 
      array[i]=newArray[i]; 
     } 
     array[arraySize-1]=maxElement; 
     return 1; 
    } 

} 
+2

'inDecOrder'는'int inDecOrder = 1; '처럼 초기화합니다. – BLUEPIXY

+0

[컴파일러 경고를 활성화하고 오류로 처리하십시오.] (http://coliru.stacked-crooked.com/a/ddaf7de1df80c3fa). – WhozCraig

+0

, 감사합니다. – yenchy1

답변

0

표준 입출력 라이브러리 버퍼 출력과 하나가 줄 바꿈 출력 스트림에서 문자 ('\ n') 또는 때 명시 적으로 FFLUSH() 함수를 호출이 발생할 경우에만 진짜를 기록합니다.

관련 문제