BruteForce::getResult()   C
last analyzed

Complexity

Conditions 7
Paths 12

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 28
cts 28
cp 1
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 23
nc 12
nop 0
crap 7
1
<?php
2
3
namespace drupol\phpartition\Algorithm;
4
5
use drupol\phpartition\BasePartitionAlgorithm;
6
use drupol\phpartition\PartitionAlgorithmInterface;
7
use drupol\phpermutations\Generators\Permutations;
8
9
/**
10
 * Class BruteForce.
11
 *
12
 * @package drupol\phpartition\Algorithm
13
 */
14
class BruteForce extends BasePartitionAlgorithm implements PartitionAlgorithmInterface
15
{
16
17
  /**
18
   * {@inheritdoc}
19
   */
20 3
    public function getResult()
21
    {
22 3
        $this->getDataPartition()->sortByValue('ASC');
23 3
        $partitionSize = ($this->getSize() > $this->getDataPartition()->size()) ?
24 3
          $this->getDataPartition()->size() :
25 3
          $this->getSize();
26
27 3
        for ($p = $partitionSize; $p > 1; $p--) {
28 3
            $best = $this->getDataPartition()->getWeight();
29 3
            $target = ($best) / $p;
30 3
            $goodSubset = array();
31 3
            $maxSize = floor($this->getDataPartition()->size() / $p);
32
33 3
            for ($i = 1; $i <= $maxSize; $i++) {
34 3
                $permutations = new Permutations($this->getDataPartition()->toArray(), $i);
35 3
                foreach ($permutations->generator() as $subset) {
36 3
                    $x = 0;
37 3
                    foreach ($subset as $item) {
38 3
                        $x += $item->getValue();
39 3
                        if (abs($x - $target) - abs($best - $target) < 0) {
40 3
                            $best = $x;
41 3
                            $goodSubset = $subset;
42 3
                        }
43 3
                    }
44 3
                }
45 3
            }
46
47 3
            $this->getPartitionContainer()->insert($this->getPartition()->addItems($goodSubset));
48 3
            $this->getDataPartition()->deleteItems($goodSubset);
49 3
        }
50
51 3
        $this->getPartitionContainer()->insert($this->getPartition()->addItems($this->getDataPartition()->toArray()));
52
53 3
        return $this->getPartitionContainer()->getPartitionsItemsArray();
54
    }
55
}
56