|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace drupol\phpartition\Algorithm; |
|
4
|
|
|
|
|
5
|
|
|
use drupol\phpartition\BasePartitionAlgorithm; |
|
6
|
|
|
use drupol\phpartition\Partition; |
|
7
|
|
|
use drupol\phpartition\PartitionAlgorithmInterface; |
|
8
|
|
|
use drupol\phpermutations\Permutations; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class BruteForce. |
|
12
|
|
|
* |
|
13
|
|
|
* @package drupol\phpartition\Algorithm |
|
14
|
|
|
*/ |
|
15
|
|
|
class BruteForce extends BasePartitionAlgorithm implements PartitionAlgorithmInterface { |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* {@inheritdoc} |
|
19
|
|
|
*/ |
|
20
|
2 |
|
public function getResult() { |
|
21
|
2 |
|
$this->getDataPartition()->sortByValue('ASC'); |
|
22
|
2 |
|
$partitionSize = ($this->getSize() > $this->getDataPartition()->count()) ? $this->getDataPartition()->count() : $this->getSize(); |
|
23
|
|
|
|
|
24
|
2 |
|
for ($p = $partitionSize; $p > 1; $p--) { |
|
25
|
2 |
|
$best = $this->getDataPartition()->getWeight(); |
|
26
|
2 |
|
$target = ($best) / $p; |
|
27
|
2 |
|
$goodSubset = array(); |
|
28
|
2 |
|
$maxSize = floor($this->getDataPartition()->count() / $p); |
|
29
|
|
|
|
|
30
|
2 |
|
for ($i = 1; $i <= $maxSize; $i++) { |
|
31
|
2 |
|
$permutations = new Permutations($this->getDataPartition()->values(), $i); |
|
32
|
2 |
|
foreach ($permutations->generator() as $subset) { |
|
33
|
2 |
|
$x = 0; |
|
34
|
2 |
|
foreach ($subset as $item) { |
|
35
|
2 |
|
$x += $item->getValue(); |
|
36
|
2 |
|
if (abs($x - $target) - abs($best - $target) < 0) { |
|
37
|
2 |
|
$best = $x; |
|
38
|
2 |
|
$goodSubset = $subset; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
2 |
|
$partition = new Partition(); |
|
45
|
2 |
|
$partition->setAlgo($this); |
|
46
|
2 |
|
$partition->addItems($goodSubset); |
|
47
|
2 |
|
$this->getPartitionContainer()->insert($partition); |
|
48
|
2 |
|
$this->getDataPartition()->deleteItems($goodSubset); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
$partition = new Partition(); |
|
52
|
2 |
|
$partition->setAlgo($this); |
|
53
|
2 |
|
$partition->addItems($this->getDataPartition()->all()); |
|
54
|
2 |
|
$this->getPartitionContainer()->insert($partition); |
|
55
|
|
|
|
|
56
|
2 |
|
return $this->getPartitionContainer()->getPartitionsItemsArray(); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
|