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

Permutator::generateFixedLengthPermutations()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 2
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
ccs 10
cts 10
cp 1
crap 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