Passed
Push — master ( 65ca73...10de3a )
by Pol
02:10
created

Permutations::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace drupol\phpermutations\Generators;
4
5
use drupol\phpermutations\Combinatorics;
6
7
/**
8
 * Class Permutations.
9
 *
10
 * @package drupol\phpermutations\Generators
11
 *
12
 * Inspired by the work of Mark Wilson <[email protected]>
13
 */
14
class Permutations extends Combinatorics
15
{
16
    /**
17
     * The combinations generator.
18
     *
19
     * @var \drupol\phpermutations\Generators\Combinations
20
     */
21
    protected $combinations;
22
23
    /**
24
     * Combinatorics constructor.
25
     *
26
     * @param array $dataset
27
     *   The dataset.
28
     * @param int|null $length
29
     *   The length.
30
     */
31
    public function __construct(array $dataset = [], $length = null)
32
    {
33
        parent::__construct($dataset, $length);
34
        $this->combinations = new Combinations($dataset, $this->getLength());
35
    }
36
37
    /**
38
     * Alias of the get() method.
39
     *
40
     * @codingStandardsIgnoreStart
41
     * @return \Generator
42
     * @codingStandardsIgnoreEnd
43
     */
44
    public function generator()
45
    {
46
        foreach ($this->combinations->generator() as $combination) {
47
            foreach ($this->get($combination) as $current) {
48
                yield $current;
49
            }
50
        }
51
    }
52
53
    /**
54
     * Convert the generator into an array.
55
     *
56
     * @return array
57
     *   The elements.
58
     */
59
    public function toArray()
60
    {
61
        $data = [];
62
63
        foreach ($this->generator() as $value) {
64
            $data[] = $value;
65
        }
66
67
        return $data;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function count()
74
    {
75
        return $this->combinations->count() * $this->fact($this->getLength());
76
    }
77
78
    /**
79
     * The permutations generator.
80
     *
81
     * @param array $dataset
82
     *   The dataset.
83
     *
84
     * @codingStandardsIgnoreStart
85
     * @return \Generator
86
     * @codingStandardsIgnoreEnd
87
     */
88
    protected function get(array $dataset)
89
    {
90
        foreach ($dataset as $key => $firstItem) {
91
            $remaining = $dataset;
92
            array_splice($remaining, $key, 1);
93
            if (count($remaining) === 0) {
94
                yield [$firstItem];
95
96
                continue;
97
            }
98
            foreach ($this->get($remaining) as $permutation) {
99
                array_unshift($permutation, $firstItem);
100
                yield $permutation;
101
            }
102
        }
103
    }
104
}
105