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 GreedyAltAlt. |
13
|
|
|
*/ |
14
|
|
|
class GreedyAltAlt extends Partitioner |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* {@inheritdoc} |
18
|
|
|
*/ |
19
|
|
|
protected function fillPartitions(Partitions $partitions, Partition $dataset, int $chunks): void |
20
|
|
|
{ |
21
|
|
|
// Edge case handling. |
22
|
|
|
if ($dataset->count() === $chunks) { |
23
|
|
|
foreach ($dataset as $key => $item) { |
24
|
|
|
$partitions->partition((int) $key)->exchangeArray([$item]); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
// Edge case handling. |
31
|
|
|
if (0 === $chunks) { |
32
|
|
|
throw new \InvalidArgumentException('Chunks must be different from 0.'); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
// Greedy needs a dataset sorted DESC. |
36
|
|
|
$dataset->uasort( |
37
|
|
|
static function (PartitionItem $left, PartitionItem $right) { |
38
|
|
|
return $left->getWeight() <=> $right->getWeight(); |
39
|
|
|
} |
40
|
|
|
); |
41
|
|
|
|
42
|
|
|
$partitionsArray = []; |
43
|
|
|
$best = $dataset->getWeight() / $chunks; |
44
|
|
|
|
45
|
|
|
for ($p = 1; $p < $chunks; ++$p) { |
46
|
|
|
$partition = $this->getPartitionFactory()::create(); |
47
|
|
|
|
48
|
|
|
while ($partition->getWeight() < $best && 1 < $dataset->count()) { |
49
|
|
|
$bounds = $dataset->getBounds(); |
50
|
|
|
// Get the key of the item with the lowest value. |
51
|
|
|
$key = $bounds[0]; |
52
|
|
|
|
53
|
|
|
if (0 === $partition->count()) { |
54
|
|
|
// Get the key of the item with the highest value. |
55
|
|
|
$key = $bounds[1]; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$partition->append($dataset[$key]); |
59
|
|
|
unset($dataset[$key]); |
60
|
|
|
$dataset->exchangeArray(\array_values($dataset->getArrayCopy())); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$partitionsArray[] = $partition; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$partitionsArray[] = $dataset; |
67
|
|
|
|
68
|
|
|
foreach ($partitionsArray as $key => $subset) { |
69
|
|
|
$partitions->partition($key)->exchangeArray($subset); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|