Completed
Pull Request — master (#2)
by Pol
04:12
created

Greedy::fillPartitions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 3
dl 0
loc 17
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace drupol\phpartition;
6
7
use drupol\phpartition\Partition\Partition;
8
use drupol\phpartition\Partitions\Partitions;
9
10
/**
11
 * Class Greedy.
12
 */
13
class Greedy extends Partitioner
14
{
15
    /**
16
     * @param \drupol\phpartition\Partitions\Partitions $partitions
17
     * @param \drupol\phpartition\Partition\Partition $dataset
18
     * @param int $chunks
19
     */
20
    protected function fillPartitions(Partitions $partitions, Partition $dataset, int $chunks): void
21
    {
22
        $partitionItemFactory = $this->getPartitionItemFactory();
23
24
        // Greedy needs a dataset sorted DESC.
25
        $dataset->uasort(static function ($a, $b) use ($partitionItemFactory) {
26
            $left = $partitionItemFactory::create($a);
27
            $right = $partitionItemFactory::create($b);
28
29
            return $right->getWeight() <=> $left->getWeight();
30
        });
31
32
        foreach ($dataset as $data) {
33
            $partitions
34
                ->sort()
35
                ->partition(0)
36
                ->append($data);
37
        }
38
    }
39
}
40