Would somebody help me with this.
Let's take 4! (4 times 3 times 2 times 1 time = 24). This is easy to do but I want to have all 24 combinations on the screen.
Thanks
Would somebody help me with this.
Let's take 4! (4 times 3 times 2 times 1 time = 24). This is easy to do but I want to have all 24 combinations on the screen.
Thanks
There is a little code that will do it for 2!. You can expand on that for 4!.Code:for (x=2; x>0; x--) { for (y=2; y>0; y--) { if(y==x) continue; cout<<x<<","<<y<<endl; } }
You are creating *permutations*.
Here is a function for creating all permutations in order (there is one in STL too called next_permutation using templates):
Code:#include <iostream> void swap(int &n1,int &n2) { int temp=n1; n1=n2; n2=temp; } bool next_permutation(int *table, int length) { int key=length-1, i=length-1; while(key>0 && table[key]<=table[key-1]) key--; if(key==0)return false; key--; while(table[key]>=table[i]) i--; swap(table[key],table[i]); for(i=length-1,key++;key<i;key++,i--) swap(table[key],table[i]); return true; } int main () { int i, sequence[10]={1,2,3,4,5,6,7,8,9,10}; do { for(i=0;i<10;i++) std::cout<<sequence[i]<<" "; std::cout<<std::endl; } while(next_permutation(sequence,10)); return 0; }
Thanks for the solutions. Is it possible to get a solution so I don't have to specify in advance the number of elements in the array.
Fero
I''m just guessing 'cuz I didn't look carefully (I'm probably wrong, but whatever), but looking at golfinguy's post, try this:
again, this is a wild guess based on a quick glance at golfinguy's post...Code:void showStuff(int n) { for (x=n; x>0; x--) { for (y=n; y>0; y--) { if(y==x) continue; cout<<x<<","<<y<<endl; } } }
Just Google It. √
(\ /)
( . .)
c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.