|
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 GreedyAltAlt. |
|
12
|
|
|
*/ |
|
13
|
|
|
class GreedyAltAlt extends Partitioner |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* {@inheritdoc} |
|
17
|
|
|
*/ |
|
18
|
|
|
protected function fillPartitions(Partitions $partitions, Partition $dataset, int $chunks): void |
|
19
|
|
|
{ |
|
20
|
|
|
$partitionItemFactory = $this->getPartitionItemFactory(); |
|
21
|
|
|
|
|
22
|
|
|
// Greedy needs a dataset sorted DESC. |
|
23
|
|
|
$dataset->uasort(static function ($a, $b) use ($partitionItemFactory) { |
|
24
|
|
|
$left = $partitionItemFactory::create($a); |
|
25
|
|
|
$right = $partitionItemFactory::create($b); |
|
26
|
|
|
|
|
27
|
|
|
return $right->getWeight() <=> $left->getWeight(); |
|
28
|
|
|
}); |
|
29
|
|
|
|
|
30
|
|
|
$partitionsArray = []; |
|
31
|
|
|
|
|
32
|
|
|
for ($p = $chunks; 1 < $p; --$p) { |
|
33
|
|
|
$partition = new Partition(); |
|
34
|
|
|
$best = $dataset->getWeight() / $chunks; |
|
35
|
|
|
|
|
36
|
|
|
while ($partition->getWeight() < $best && !empty($dataset)) { |
|
37
|
|
|
$key = $this->findOptimalItemKey($partition, $dataset, $best); |
|
38
|
|
|
$partition->append($dataset[$key]); |
|
39
|
|
|
unset($dataset[$key]); |
|
40
|
|
|
$dataset->exchangeArray(\array_values($dataset->getArrayCopy())); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$partitionsArray[] = $partition; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$partitionsArray[] = $dataset; |
|
47
|
|
|
|
|
48
|
|
|
foreach ($partitionsArray as $key => $subset) { |
|
49
|
|
|
$partitions->partition($key)->exchangeArray($subset); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param \drupol\phpartition\Partition\Partition $partition |
|
55
|
|
|
* @param \drupol\phpartition\Partition\Partition $dataset |
|
56
|
|
|
* @param float $best |
|
57
|
|
|
* |
|
58
|
|
|
* @return null|false|int|string |
|
59
|
|
|
*/ |
|
60
|
|
|
private function findOptimalItemKey(Partition $partition, Partition $dataset, $best) |
|
|
|
|
|
|
61
|
|
|
{ |
|
62
|
|
|
if (0 === $partition->count()) { |
|
63
|
|
|
\reset($dataset); |
|
|
|
|
|
|
64
|
|
|
|
|
65
|
|
|
return \key($dataset); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
\end($dataset); |
|
|
|
|
|
|
69
|
|
|
|
|
70
|
|
|
return \key($dataset); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.