1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
Condorcet PHP Class, with Schulze Methods and others ! |
4
|
|
|
|
5
|
|
|
By Julien Boudry - MIT LICENSE (Please read LICENSE.txt) |
6
|
|
|
https://github.com/julien-boudry/Condorcet |
7
|
|
|
*/ |
8
|
|
|
declare(strict_types=1); |
9
|
|
|
|
10
|
|
|
namespace Condorcet\Algo\Tools; |
11
|
|
|
|
12
|
|
|
// Thanks to Jorge Gomes @cyberkurumin |
13
|
|
|
class Permutation |
14
|
|
|
{ |
15
|
|
|
private const PREFIX = 'C'; |
16
|
|
|
|
17
|
|
|
public $results = []; |
18
|
|
|
|
19
|
1 |
|
public static function countPossiblePermutations (int $candidatesNumber) : int { |
20
|
1 |
|
$result = $candidatesNumber; |
21
|
|
|
|
22
|
1 |
|
for ($iteration = 1; $iteration < $candidatesNumber; $iteration++) : |
23
|
1 |
|
$result = $result * ($candidatesNumber - $iteration); |
24
|
|
|
endfor; |
25
|
|
|
|
26
|
1 |
|
return $result; |
27
|
|
|
} |
28
|
|
|
|
29
|
1 |
|
public function __construct($arr) { |
30
|
1 |
|
$this->_exec( |
31
|
1 |
|
$this->_permute( (is_int($arr)) ? $this->createCandidates($arr) : $arr ) |
32
|
|
|
); |
33
|
1 |
|
} |
34
|
|
|
|
35
|
1 |
|
public function getResults (bool $serialize = false) { |
36
|
1 |
|
return ($serialize) ? serialize($this->results) : $this->results; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function writeResults (string $path) : void { |
40
|
|
|
file_put_contents($path, $this->getResults(true)); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
protected function createCandidates (int $numberOfCandidates) : array |
44
|
|
|
{ |
45
|
1 |
|
$arr = []; |
46
|
|
|
|
47
|
1 |
|
for ($i = 0; $i < $numberOfCandidates; $i++) { |
48
|
1 |
|
$arr[] = self::PREFIX.$i; |
49
|
|
|
} |
50
|
1 |
|
return $arr; |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
private function _exec($a, array $i = []) : void { |
54
|
1 |
|
if (is_array($a)) : |
55
|
1 |
|
foreach($a as $k => $v) : |
56
|
1 |
|
$i2 = $i; |
57
|
1 |
|
$i2[] = $k; |
58
|
|
|
|
59
|
1 |
|
$this->_exec($v, $i2); |
60
|
|
|
endforeach; |
61
|
|
|
else : |
62
|
1 |
|
$i[] = $a; |
63
|
|
|
|
64
|
|
|
// Del 0 key, first key must be 1. |
65
|
1 |
|
$r = [0=>null]; $r = array_merge($r,$i); unset($r[0]); |
66
|
|
|
|
67
|
1 |
|
$this->results[] = $r; |
68
|
|
|
endif; |
69
|
1 |
|
} |
70
|
|
|
|
71
|
1 |
|
private function _permute(array $arr) { |
72
|
1 |
|
$out = []; |
73
|
|
|
|
74
|
1 |
|
if (count($arr) > 1) : |
75
|
1 |
|
foreach($arr as $r => $c) : |
76
|
1 |
|
$n = $arr; |
77
|
1 |
|
unset($n[$r]); |
78
|
1 |
|
$out[$c] = $this->_permute($n); |
79
|
|
|
endforeach; |
80
|
|
|
else : |
81
|
1 |
|
return array_shift($arr); |
82
|
|
|
endif; |
83
|
|
|
|
84
|
1 |
|
return $out; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|