Passed
Push — master ( a2fa16...8a4497 )
by Pol
11:27
created

Combinations   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 12
c 2
b 0
f 0
dl 0
loc 37
ccs 11
cts 11
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 17 4
A generator() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace drupol\phpermutations\Generators;
6
7
use drupol\phpermutations\GeneratorInterface;
8
use drupol\phpermutations\Iterators\Combinations as CombinationsIterator;
9
use Generator;
10
11
use function array_slice;
12
use function count;
13
14
/**
15
 * Class Combinations.
16
 *
17
 * @author Mark Wilson <[email protected]>
18
 */
19 6
class Combinations extends CombinationsIterator implements GeneratorInterface
20
{
21 6
    /**
22
     * {@inheritdoc}
23
     */
24
    public function generator()
25
    {
26
        return $this->get($this->getDataset(), $this->getLength());
27 4
    }
28
29 4
    /**
30
     * The generator.
31 4
     *
32 4
     * @param array<int, mixed> $dataset
33
     *                       The dataset
34
     * @param int   $length
35 4
     *                       The length
36
     *
37
     * @return Generator<array>
38
     */
39
    protected function get(array $dataset, $length)
40
    {
41
        $originalLength = count($dataset);
42
        $remainingLength = $originalLength - $length + 1;
43
44
        for ($i = 0; $i < $remainingLength; ++$i) {
45
            $current = $dataset[$i];
46
47
            if (1 === $length) {
48
                yield [$current];
49
            } else {
50
                $remaining = array_slice($dataset, $i + 1);
51 6
52
                foreach ($this->get($remaining, $length - 1) as $permutation) {
53 6
                    array_unshift($permutation, $current);
54 6
55 6
                    yield $permutation;
56 6
                }
57 6
            }
58 6
        }
59
    }
60
}
61