1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace drupol\phpartition\Algorithm; |
4
|
|
|
|
5
|
|
|
use drupol\phpartition\BasePartitionAlgorithm; |
6
|
|
|
use drupol\phpartition\PartitionAlgorithmInterface; |
7
|
|
|
use drupol\phpartition\Subset; |
8
|
|
|
use Math\Combinatorics\Permutation; |
9
|
|
|
use Oefenweb\Statistics\Statistics; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class BruteForceCustomA. |
13
|
|
|
* |
14
|
|
|
* @package drupol\phpartition\Algorithm |
15
|
|
|
*/ |
16
|
|
|
class BruteForceCustomA extends BasePartitionAlgorithm implements PartitionAlgorithmInterface { |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @inheritdoc |
20
|
|
|
*/ |
21
|
2 |
|
public function getResult() { |
22
|
2 |
|
$permutation = new Permutation(); |
23
|
2 |
|
$this->dataset->sortByValue('ASC'); |
24
|
2 |
|
$variance = pow(2, $this->dataset->count()); |
25
|
|
|
|
26
|
2 |
|
foreach ($permutation->getPermutations($this->dataset->getItems(), $this->dataset->count()) as $subset) { |
27
|
2 |
|
$subsetChunks = array_chunk($subset, $this->getPartition()); |
28
|
|
|
|
29
|
2 |
|
$phpartitionSubsetSums = array(); |
|
|
|
|
30
|
2 |
|
foreach ($subsetChunks as $items) { |
31
|
2 |
|
$phpartitionSubset = new Subset(); |
32
|
2 |
|
$phpartitionSubset->setItems($items); |
33
|
2 |
|
$phpartitionSubsetSums[] = $phpartitionSubset->getWeight(); |
34
|
2 |
|
} |
35
|
|
|
|
36
|
2 |
|
$varianceCandidate = Statistics::variance($phpartitionSubsetSums); |
37
|
2 |
|
if ($varianceCandidate < $variance) { |
38
|
2 |
|
$variance = $varianceCandidate; |
39
|
2 |
|
$best = $subsetChunks; |
40
|
2 |
|
} |
41
|
2 |
|
} |
42
|
|
|
|
43
|
2 |
|
foreach($best as $subsetChunks) { |
|
|
|
|
44
|
2 |
|
$subset = new Subset(); |
45
|
2 |
|
$subset->setAlgo($this); |
46
|
2 |
|
$subset->setItems($subsetChunks); |
47
|
2 |
|
$this->getSubsetContainer()->insert($subset); |
48
|
2 |
|
} |
49
|
|
|
|
50
|
2 |
|
return $this->getSubsetContainer()->getSubsetsAndItemsAsArray(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @inheritdoc |
55
|
|
|
*/ |
56
|
2 |
|
public function getSubsetWeight(Subset $subset) { |
57
|
|
|
// Unused |
58
|
2 |
|
} |
59
|
|
|
|
60
|
|
|
} |
Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.