Permutation::writeResults()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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