SackFiller   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 21
c 1
b 0
f 0
dl 0
loc 44
ccs 23
cts 23
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B fill() 0 34 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Samdark\Sack;
6
7
final class SackFiller
8
{
9 1
    public function __construct(
10
        private int $volume
11
    ) {
12 1
    }
13
14
    /**
15
     * @param Item[] $items
16
     */
17 1
    public function fill(array $items): Sack
18
    {
19 1
        $matrix = [0 => array_fill(0, $this->volume + 1, 0)];
20
21
        /** @var int $i */
22 1
        foreach ($items as $i => $item) {
23 1
            for ($volume = 0; $volume <= $this->volume; $volume++) {
24 1
                if ($item->getVolume() > $volume) {
25 1
                    $matrix[$i + 1][$volume] = $matrix[$i][$volume];
26
                } else {
27 1
                    $matrix[$i + 1][$volume] = max(
28 1
                        $matrix[$i][$volume],
29 1
                        $matrix[$i][$volume - $item->getVolume()] + $item->getValue()
30 1
                    );
31
                }
32
            }
33
        }
34 1
        $maximumValue = $matrix[count($items)][$this->volume];
35
36 1
        $result = [];
37 1
        $valueReminder = $maximumValue;
38 1
        $volumeReminder = $this->volume;
39
40 1
        for ($i = count($items); $i > 0 && $valueReminder > 0; $i--) {
41 1
            if ($valueReminder !== $matrix[$i - 1][$volumeReminder]) {
42 1
                $resultItem = $items[$i - 1];
43 1
                $result[] = $resultItem;
44
45 1
                $valueReminder -= $resultItem->getValue();
46 1
                $volumeReminder -= $resultItem->getVolume();
47
            }
48
        }
49
50 1
        return new Sack($result, $maximumValue);
51
    }
52
}
53