Passed
Pull Request — master (#2)
by Pol
04:33
created

GreedyAltAltAlt::fillPartitions()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 22
nc 6
nop 3
dl 0
loc 37
rs 9.568
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace drupol\phpartition;
6
7
use drupol\phpartition\Contract\PartitionItem;
8
use drupol\phpartition\Partition\Partition;
9
use drupol\phpartition\Partitions\Partitions;
10
11
/**
12
 * Class Greedy.
13
 */
14
class GreedyAltAltAlt extends Partitioner
15
{
16
    /**
17
     * @param \drupol\phpartition\Partitions\Partitions $partitions
18
     * @param \drupol\phpartition\Partition\Partition $dataset
19
     * @param int $chunks
20
     */
21
    protected function fillPartitions(Partitions $partitions, Partition $dataset, int $chunks): void
22
    {
23
        // Greedy needs a dataset sorted DESC.
24
        $dataset->uasort(
25
            static function (PartitionItem $left, PartitionItem $right) {
26
                return $right->getWeight() <=> $left->getWeight();
27
            }
28
        );
29
30
        $partitionsArray = [];
31
        $best = $dataset->getWeight() / $chunks;
32
33
        for ($p = 1; $p < $chunks; ++$p) {
34
            $partition = $this->getPartitionFactory()::create();
35
36
            \reset($dataset);
0 ignored issues
show
Bug introduced by
$dataset of type drupol\phpartition\Partition\Partition is incompatible with the type array expected by parameter $array of reset(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

36
            \reset(/** @scrutinizer ignore-type */ $dataset);
Loading history...
37
            $key = \key($dataset);
38
            $partition->append($dataset[$key]);
39
            unset($dataset[$key]);
40
            $dataset->exchangeArray(\array_values(\array_reverse($dataset->getArrayCopy())));
41
42
            while ($partition->getWeight() < $best) {
43
                \reset($dataset);
44
                $key = \key($dataset);
45
                $partition->append($dataset[$key]);
46
                unset($dataset[$key]);
47
            }
48
49
            $partitionsArray[] = $partition;
50
51
            $dataset->exchangeArray(\array_values(\array_reverse($dataset->getArrayCopy())));
52
        }
53
54
        $partitionsArray[] = $dataset;
55
56
        foreach ($partitionsArray as $key => $subset) {
57
            $partitions->partition($key)->exchangeArray($subset);
58
        }
59
    }
60
}
61