<?php
$arr = [ 1,2,3,4 ];
$expected = [
'1-2-3-4',
'2-1-3-4',
'3-1-2-4',
'1-3-2-4',
'2-3-1-4',
'3-2-1-4',
'4-2-1-3',
'2-4-1-3',
'1-4-2-3',
'4-1-2-3',
'2-1-4-3',
'1-2-4-3',
'1-3-4-2',
'3-1-4-2',
'4-1-3-2',
'1-4-3-2',
'3-4-1-2',
'4-3-1-2',
'4-3-2-1',
'3-4-2-1',
'2-4-3-1',
'4-2-3-1',
'3-2-4-1',
'2-3-4-1',
];
function mixture( $size, array &$collection ) {
$permutations = [];
$offset = $size - 1;
if ( 1 === $size ) {
$permutations[] = implode( '-', $collection );
return $permutations;
}
for ( $i = 0; $i < $offset; $i++ ) {
$permutations = array_merge( $permutations, mixture( $offset, $collection ) );
$j = ( 0 == $size % 2 ) ? $i : 0;
$tmp_el = $collection[ $offset ];
$collection[ $offset ] = $collection[ $j ];
$collection[ $j ] = $tmp_el;
}
$permutations = array_merge( $permutations, mixture( $offset, $collection ) );
return $permutations;
}
print_r($permutations = mixture( count($arr), $arr ));
if ($expected == $permutations) {
echo 'PASS'.PHP_EOL;
} else {
echo 'FAIL'.PHP_EOL;
echo 'missing: '.PHP_EOL;
print_r(array_diff($expected, array_unique($permutations)));
}
preferences:
25.73 ms | 403 KiB | 5 Q