fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void ProcessThePermutation(int *arr, int arrLen)
  5. {
  6. while(--arrLen >= 0)
  7. cout << *arr++;
  8. cout << endl;
  9. }
  10.  
  11. void ProcessAllPermutations(int arr[], int arrLen, int permLen)
  12. {
  13. if(permLen == 1)
  14. ProcessThePermutation(arr, arrLen); // print the permutation
  15. else
  16. {
  17. int lastpos = permLen - 1; // last item position for swaps
  18.  
  19. for(int pos = lastpos; pos >= 0; pos--) // pos of item to swap with the last
  20. {
  21. swap(arr[pos], arr[lastpos]); // put the chosen item at the end
  22. ProcessAllPermutations(arr, arrLen, permLen - 1);
  23. swap(arr[pos], arr[lastpos]); // put the chosen item back at pos
  24. }
  25. }
  26. }
  27.  
  28. int main() {
  29. // your code goes here
  30. int arr[] = {2, 4, 7, 8};
  31. ProcessAllPermutations(arr, 4, 4);
  32. return 0;
  33. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
2478
4278
2748
7248
7428
4728
2487
4287
2847
8247
8427
4827
2874
8274
2784
7284
7824
8724
8472
4872
8742
7842
7482
4782