fork download
  1. <?php
  2. test();
  3.  
  4. function joiner($a) { return join(', ', $a); }
  5. function test() {
  6. $test = ['a','b','c','d'];
  7. $N = 3;
  8.  
  9. $r = getSequenses( $N, $test);
  10. print_r( array_map( 'joiner', $r));
  11. }
  12.  
  13. function getSequenses( $N, $arr) {
  14. $L = count($arr);
  15. if( $L > 32) throw new Exception("Массив длиннее 32 элементов");
  16. $result = [];
  17.  
  18. for( $i=0; $i<pow( 2, $L); $i++) {
  19. if( $N != countBits( $i)) continue;
  20.  
  21. // get all permutations
  22. $set = array();
  23. $bits = $i;
  24. for( $j=0; $bits; $j++) {
  25. if( !($bits & 1)) {
  26. $bits = $bits >> 1;
  27. continue;
  28. }
  29. array_push( $set, $arr[ $j]);
  30. $bits = $bits >> 1;
  31. }
  32.  
  33. $result = array_merge( $result, permute( $set));
  34. }
  35.  
  36. return $result;
  37.  
  38. }
  39.  
  40. function permute( $items, $perms = array(), &$result = array()) {
  41. if( empty( $items)) {
  42. array_push( $result, $perms);
  43. } else {
  44. for( $i = count( $items) - 1; $i >= 0; --$i) {
  45. $newitems = $items;
  46. $newperms = $perms;
  47. list($foo) = array_splice($newitems, $i, 1);
  48. array_unshift($newperms, $foo);
  49. permute( $newitems, $newperms, $result);
  50. }
  51. }
  52.  
  53. return $result;
  54. }
  55.  
  56. function countBits( $n) {
  57. $count = 0;
  58. while( $n) {
  59. $count += ( $n & 1);
  60. $n = $n >> 1;
  61. }
  62.  
  63. return $count;
  64. }
Success #stdin #stdout 0.04s 52480KB
stdin
Standard input is empty
stdout
Array
(
    [0] => a, b, c
    [1] => b, a, c
    [2] => a, c, b
    [3] => c, a, b
    [4] => b, c, a
    [5] => c, b, a
    [6] => a, b, d
    [7] => b, a, d
    [8] => a, d, b
    [9] => d, a, b
    [10] => b, d, a
    [11] => d, b, a
    [12] => a, c, d
    [13] => c, a, d
    [14] => a, d, c
    [15] => d, a, c
    [16] => c, d, a
    [17] => d, c, a
    [18] => b, c, d
    [19] => c, b, d
    [20] => b, d, c
    [21] => d, b, c
    [22] => c, d, b
    [23] => d, c, b
)