Passed
Push — master ( 18bdd2...b79ef4 )
by Pol
04:33
created

Combinations::generator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace drupol\phpermutations\Generators;
4
5
use drupol\phpermutations\Iterators\Combinations as CombinationsIterator;
6
7
/**
8
 * Class Combinations.
9
 *
10
 * @package drupol\phpermutations\Generators
11
 *
12
 * @author Mark Wilson <[email protected]>
13
 */
14
class Combinations extends CombinationsIterator
15
{
16
    /**
17
     * Alias of the get() method.
18
     *
19
     * @return \Generator
20
     *   The prime generator.
21
     */
22 6
    public function generator()
23
    {
24 6
        return $this->get($this->getDataset(), $this->getLength());
25
    }
26
27
    /**
28
     * Convert the generator into an array.
29
     *
30
     * @return array
31
     *   The elements.
32
     */
33 4
    public function toArray()
34
    {
35 4
        $data = [];
36
37 4
        foreach ($this->generator() as $value) {
38 4
            $data[] = $value;
39 4
        }
40
41 4
        return $data;
42
    }
43
44
    /**
45
     * The generator.
46
     *
47
     * @param array $dataset
48
     *   The dataset.
49
     * @param int $length
50
     *   The length.
51
     *
52
     * @codingStandardsIgnoreStart
53
     * @return \Generator
54
     * @codingStandardsIgnoreEnd
55
     */
56 6
    protected function get(array $dataset, $length)
57
    {
58 6
        $originalLength = count($dataset);
59 6
        $remainingLength = $originalLength - $length + 1;
60 6
        for ($i = 0; $i < $remainingLength; $i++) {
61 6
            $current = $dataset[$i];
62 6
            if ($length === 1) {
63 6
                yield [$current];
64 6
            } else {
65 6
                $remaining = array_slice($dataset, $i + 1);
66 6
                foreach ($this->get($remaining, $length - 1) as $permutation) {
67 6
                    array_unshift($permutation, $current);
68 6
                    yield $permutation;
69 6
                }
70
            }
71 6
        }
72 6
    }
73
}
74