1 | <?php |
||
2 | /** |
||
3 | * Box packing (3D bin packing, knapsack problem). |
||
4 | * |
||
5 | * @author Doug Wright |
||
6 | */ |
||
7 | declare(strict_types=1); |
||
8 | |||
9 | namespace DVDoug\BoxPacker; |
||
10 | |||
11 | use ArrayIterator; |
||
12 | use Countable; |
||
13 | use IteratorAggregate; |
||
14 | use Traversable; |
||
15 | |||
16 | use function array_map; |
||
17 | use function count; |
||
18 | use function usort; |
||
19 | |||
20 | /** |
||
21 | * List of packed items, ordered by volume. |
||
22 | */ |
||
23 | class PackedItemList implements Countable, IteratorAggregate |
||
24 | { |
||
25 | /** |
||
26 | * @var PackedItem[] |
||
27 | */ |
||
28 | private array $list = []; |
||
29 | |||
30 | private int $weight = 0; |
||
31 | |||
32 | private int $volume = 0; |
||
33 | |||
34 | private bool $isSorted = false; |
||
35 | |||
36 | 96 | public function insert(PackedItem $item): void |
|
37 | { |
||
38 | 96 | $this->list[] = $item; |
|
39 | 96 | $this->weight += $item->item->getWeight(); |
|
40 | 96 | $this->volume += $item->width * $item->length * $item->depth; |
|
41 | } |
||
42 | |||
43 | /** |
||
44 | * @return Traversable<PackedItem> |
||
45 | */ |
||
46 | 85 | public function getIterator(): Traversable |
|
47 | { |
||
48 | 85 | if (!$this->isSorted) { |
|
49 | 85 | usort($this->list, $this->compare(...)); |
|
50 | 85 | $this->isSorted = true; |
|
51 | } |
||
52 | |||
53 | 85 | return new ArrayIterator($this->list); |
|
54 | } |
||
55 | |||
56 | /** |
||
57 | * Number of items in list. |
||
58 | */ |
||
59 | 99 | public function count(): int |
|
60 | { |
||
61 | 99 | return count($this->list); |
|
62 | } |
||
63 | |||
64 | /** |
||
65 | * Get copy of this list as a standard PHP array. |
||
66 | * |
||
67 | * @internal |
||
68 | * |
||
69 | * @return Item[] |
||
70 | */ |
||
71 | 8 | public function asItemArray(): array |
|
72 | { |
||
73 | 8 | return array_map(fn (PackedItem $packedItem) => $packedItem->item, $this->list); |
|
74 | } |
||
75 | |||
76 | /** |
||
77 | * Get total volume of these items. |
||
78 | */ |
||
79 | 30 | public function getVolume(): int |
|
80 | { |
||
81 | 30 | return $this->volume; |
|
82 | } |
||
83 | |||
84 | /** |
||
85 | * Get total weight of these items. |
||
86 | */ |
||
87 | 99 | public function getWeight(): int |
|
88 | { |
||
89 | 99 | return $this->weight; |
|
90 | } |
||
91 | |||
92 | 72 | private function compare(PackedItem $itemA, PackedItem $itemB): int |
|
0 ignored issues
–
show
|
|||
93 | { |
||
94 | 72 | $itemAVolume = $itemA->item->getWidth() * $itemA->item->getLength() * $itemA->item->getDepth(); |
|
95 | 72 | $itemBVolume = $itemB->item->getWidth() * $itemB->item->getLength() * $itemB->item->getDepth(); |
|
96 | |||
97 | 72 | return ($itemBVolume <=> $itemAVolume) ?: ($itemB->item->getWeight() <=> $itemA->item->getWeight()); |
|
98 | } |
||
99 | } |
||
100 |
This check looks for private methods that have been defined, but are not used inside the class.