recursion - Recursive Permutation C++ -


i have problem assignment, need implement recursive permutation in c++ numbers. here code partly working, missing numbers. can't find problem is.

this code work, not right way.

this code take , array of number size of array. in case trying solve problem appears when send array longer 3 numbers. if send 3 numbers, output is:

/// 1 2 3 / 1 3 2 / 3 1 2 / 2 1 3 / 2 3 1 / 3 2 1 / 

output in case correct. when set array 4 , send size of 4 get:

/// 1 2 3 4 / 1 2 4 3 / 1 4 2 3 / 4 1 2 3 /  **2 1 3   / 2 3 1   / 3 2 1   /** 3 2 1 4 / 3 2 4 1 /  3 4 2 1 / 4 3 2 1 / 

output partly correct, numbers missing.

program should give output of possible variations of numbers in array

#include <iostream> using namespace std;  bool nextpermutation(int[],int); void swap(int&, int&); int maxind(int[],int); int minind(int[],int); void print (int[], int); bool test (int[], int); int fl=0;   int main() {     int a[]={1,2,3,4};     nextpermutation(a,4);     return 0; }   void print(int a[], int s) {     for(int i=0; i<s; i++)      {          cout<<a[i]<<" ";      }     cout<<endl; } bool nextpermutation(int a[], int s) {     int i=maxind(a,s);     if(fl==0)         print(a,s);     if(i!=0) {         swap(a[i],a[i-1]);         nextpermutation(a,s);      }      else if(i==0 && test(a,s))     {         int p=a[0];         for(int i=0; i<=s-2; i++)             a[i]=a[i+1];         fl=1;         nextpermutation(a,s-1);         a[s-1]=p;         fl=0;         nextpermutation(a,s);                 }     else          return false; }  bool test (int a[], int s) {         if (maxind(a,s)==0 && minind(a,s)==s-1)         return false;     else         return true; }  void swap(int& a, int& b) {     int t=a; a=b; b=t; }  int maxind(int a[], int s) {     int m=a[0], ind=0;     for(int i=0; i<s; i++)          if(m<a[i]) {             m=a[i];             ind=i;         }     return ind; }  int minind(int a[], int s) {     int m=a[0], ind=0;     for(int i=0; i<s; i++)          if(m>a[i]) {             m=a[i];             ind=i;         }     return ind; } 

you need send numbers of possibilities permutation.

if change main function solution. add loop in main funciton , send nextpermutation(a, i) variable i

int main() {     for(int = 1; < 5; i++) {         int a[]= {1,2,3,4};         nextpermutation(a,i);     }     return 0; } 

you should debug program , figure out s value decrasing here:

else if(i==0 && test(a,s)) {     int p=a[0];     for(int i=0; i<=s-2; i++) {         a[i]=a[i+1];     }     fl=1;     nextpermutation(a,s-1);     //*** careful decreasing s here , output gives 3 numbers. !!***     a[s]=p;     fl=0;     nextpermutation(a,s); } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -