/
permutations.php
49 lines (41 loc) · 992 Bytes
/
permutations.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
Permutation::main();
class Permutation
{
private static $lenght;
public static function main()
{
$arr = array(1,2,3,4,5);
// $arr = array("orange","banana","apple");
self::$lenght = count ($arr);
self::perm($arr);
}
private static function perm( $arr, $k = 0)
{
if ($k >= self::$lenght)
{
self::printArr($arr);
}
else
{
self::perm($arr, $k + 1);
for ($i = $k + 1; $i < self::$lenght; $i++)
{
//swap
$tmp = $arr[$k];
$arr[$k] = $arr[$i];
$arr[$i] = $tmp;
self::perm($arr, $k + 1);
//swap
$tmp = $arr[$k];
$arr[$k] = $arr[$i];
$arr[$i] = $tmp;
}
}
}
private static function printArr($arr)
{
echo (implode(", ",$arr));
echo "<br />";
}
}