fork(1) download
  1. <?php
  2.  
  3.  
  4. $array = [1, 2, 3, 4];
  5.  
  6. function getFactorial($array){
  7. $factorial = 1;
  8. for($n = 1; $n<=count($array); $n++){
  9. $factorial *= $n;
  10. }
  11. return $factorial;
  12. }
  13.  
  14. $factorial = getFactorial($array);
  15.  
  16. function getCombinations($array){
  17. $output = [];
  18. if(count($array) == 2){
  19. $iterations = 2;
  20. } else {
  21. $iterations = count($array) * 2;
  22. $halfIterations = $iterations / 2;
  23. }
  24. while($iterations > 0){
  25. $combination = [];
  26. foreach($array as $key => $value){
  27. $firstKey = array_key_first($array);
  28. if($key == array_key_last($array)){
  29. $combination[$key] = $array[$firstKey];
  30. } else {
  31. $combination[$key] = next($array);
  32. }
  33. }
  34. if($iterations <= $halfIterations){
  35. krsort($combination);
  36. }
  37. $array = $combination;
  38. $output[] = $combination;
  39. $iterations--;
  40. }
  41. return $output;
  42. }
  43.  
  44. function Main($array){
  45. $str = "";
  46. $count = (count($array) - 1);
  47. if(count($array) == 1){
  48. return $array;
  49. } else {
  50. for($n = 0; $n <= $count; $n++){
  51. $cutElement = $array[$n];
  52. unset($array[$n]);
  53. $combinations = getCombinations($array, $factorial);
  54. foreach($combinations as $key => $value){
  55. array_unshift($combinations[$key], $cutElement);
  56. $str .= implode(" ", $combinations[$key]);
  57. $str .= "\n";
  58. }
  59. $array[$n] = $cutElement;
  60. }
  61. }
  62. return $str;
  63. }
  64.  
  65. $res = Main($array);
  66. echo $res;
Success #stdin #stdout #stderr 0.02s 26412KB
stdin
Standard input is empty
stdout
1 3 4 2
1 4 2 3
1 2 3 4
1 2 4 3
1 4 3 2
1 3 2 4
2 4 1 3
2 1 3 4
2 3 4 1
2 1 4 3
2 4 3 1
2 3 1 4
3 1 2 4
3 2 4 1
3 4 1 2
3 1 4 2
3 4 2 1
3 2 1 4
4 2 3 1
4 3 1 2
4 1 2 3
4 1 3 2
4 3 2 1
4 2 1 3
stderr
PHP Notice:  Undefined variable: factorial in /home/16wb01/prog.php on line 54
PHP Notice:  Undefined variable: factorial in /home/16wb01/prog.php on line 54
PHP Notice:  Undefined variable: factorial in /home/16wb01/prog.php on line 54
PHP Notice:  Undefined variable: factorial in /home/16wb01/prog.php on line 54