Passed
Branch master (73ca69)
by Boudry
03:33
created

Permutation::_permute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 13
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 1
crap 12
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
    public static function countPossiblePermutations (int $candidatesNumber) : int {
20
        $result = $candidatesNumber;
21
22
        for ($iteration = 1; $iteration < $candidatesNumber; $iteration++) :
23
            $result = $result * ($candidatesNumber - $iteration);
24
        endfor;
25
26
        return $result;
27
    }
28
29
30
    public function __construct($arr) {
31
        $this->_exec(
32
            $this->_permute( (is_int($arr)) ? $this->createCandidates($arr) : $arr )
33
        );
34
    }
35
36
    public function getResults (bool $serialize = false) {
37
        return ($serialize) ? serialize($this->results) : $this->results;
38
    }
39
40
    public function writeResults (string $path) : void {
41
        file_put_contents($path, $this->getResults(true));
42
    }
43
44
    protected function createCandidates (int $numberOfCandidates) : array
45
    {
46
        $arr = [];
47
48
        for ($i = 0; $i < $numberOfCandidates; $i++) {
49
            $arr[] = self::PREFIX.$i;
50
        }
51
        return $arr;
52
    }
53
54
    private function _exec($a, array $i = []) : void {
55
        if (is_array($a)) :
56
            foreach($a as $k => $v) :
57
                $i2 = $i;
58
                $i2[] = $k;
59
60
                $this->_exec($v, $i2);
61
            endforeach;
62
        else :
63
            $i[] = $a;
64
65
            // Del 0 key, first key must be 1.
66
            $r = [0=>null]; $r = array_merge($r,$i); unset($r[0]);
67
68
            $this->results[] = $r;
69
        endif;
70
    }
71
72
    private function _permute(array $arr) {
73
        $out = [];
74
75
        if (count($arr) > 1) :
76
            foreach($arr as $r => $c) :
77
                $n = $arr;
78
                unset($n[$r]);
79
                $out[$c] = $this->_permute($n);
80
            endforeach;
81
        else :
82
            return array_shift($arr);
83
        endif;
84
85
        return $out;
86
    }
87
}
88