Completed
Push — master ( 72d462...18bdd2 )
by Pol
06:00 queued 04:04
created

Combinations   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
cbo 1
dl 0
loc 60
ccs 0
cts 29
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A generator() 0 4 1
A toArray() 0 10 2
A get() 0 17 4
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
    public function generator()
23
    {
24
        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
    public function toArray()
34
    {
35
        $data = [];
36
37
        foreach ($this->generator() as $value) {
38
            $data[] = $value;
39
        }
40
41
        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
    protected function get(array $dataset, $length)
57
    {
58
        $originalLength = count($dataset);
59
        $remainingLength = $originalLength - $length + 1;
60
        for ($i = 0; $i < $remainingLength; $i++) {
61
            $current = $dataset[$i];
62
            if ($length === 1) {
63
                yield [$current];
64
            } else {
65
                $remaining = array_slice($dataset, $i + 1);
66
                foreach ($this->get($remaining, $length - 1) as $permutation) {
67
                    array_unshift($permutation, $current);
68
                    yield $permutation;
69
                }
70
            }
71
        }
72
    }
73
}
74