Completed
Push — master ( 5d18c7...cabcf3 )
by Hannes
16s queued 13s
created

Permutator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 10
c 0
b 0
f 0
ccs 27
cts 27
cp 1
wmc 9
lcom 0
cbo 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getPermutations() 0 8 3
A getPowerSet() 0 20 3
A generateFixedLengthPermutations() 0 14 3
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace byrokrat\banking\Rewriter;
6
7
/**
8
 * Generate permutations for a set of values
9
 */
10
class Permutator
11
{
12
    /**
13
     * @return \Generator & iterable<array>
14
     */
15 142
    public static function getPermutations(array $set): \Generator
16
    {
17 142
        foreach (self::getPowerSet($set) as $subset) {
18 142
            foreach (self::generateFixedLengthPermutations($subset) as $perm) {
19 142
                yield $perm;
20
            }
21
        }
22 59
    }
23
24
    /**
25
     * @return array[]
26
     */
27 142
    private static function getPowerSet(array $set): array
28
    {
29 142
        $results = [[]];
30
31 142
        foreach ($set as $element) {
32 142
            foreach ($results as $combination) {
33 142
                $subset = array_merge([$element], $combination);
34 142
                $results[] = $subset;
35
            }
36
        }
37
38 142
        usort(
39 142
            $results,
40 142
            function (array $left, array $right): int {
41 142
                return count($left) <=> count($right);
42 142
            }
43
        );
44
45 142
        return array_filter($results);
46
    }
47
48
    /**
49
     * @return \Generator & iterable<array>
50
     */
51 142
    private static function generateFixedLengthPermutations(array $items, array $perms = []): \Generator
52
    {
53 142
        if (empty($items)) {
54 142
            yield $perms;
55
        } else {
56 142
            for ($i = count($items)-1; $i>=0; $i--) {
57 142
                $newitems = $items;
58 142
                $newperms = $perms;
59 142
                list($foo) = array_splice($newitems, $i, 1);
60 142
                array_unshift($newperms, $foo);
61 142
                yield from self::generateFixedLengthPermutations($newitems, $newperms);
62
            }
63
        }
64 142
    }
65
}
66