Completed
Push — master ( 9ee175...c01904 )
by Boudry
02:34
created

Permutation::_exec()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 2
crap 3
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