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