diff --git a/BoxList.php b/BoxList.php index c93460d6..3ab0a057 100644 --- a/BoxList.php +++ b/BoxList.php @@ -18,7 +18,15 @@ class BoxList extends \SplMinHeap { * @see \SplMinHeap::compare() */ public function compare($aBoxA, $aBoxB) { - return $aBoxB->getInnerVolume() - $aBoxA->getInnerVolume(); + if ($aBoxB->getInnerVolume() > $aBoxA->getInnerVolume()) { + return 1; + } + else if ($aBoxB->getInnerVolume() < $aBoxA->getInnerVolume()) { + return -1; + } + else { + return 0; + } } } diff --git a/ItemList.php b/ItemList.php index a9dad960..0120d1d8 100644 --- a/ItemList.php +++ b/ItemList.php @@ -18,7 +18,15 @@ class ItemList extends \SplMaxHeap { * @see \SplMaxHeap::compare() */ public function compare($aItemA, $aItemB) { - return $aItemA->getVolume() - $aItemB->getVolume(); + if ($aItemA->getVolume() > $aItemB->getVolume()) { + return 1; + } + else if ($aItemA->getVolume() < $aItemB->getVolume()) { + return -1; + } + else { + return 0; + } } /** diff --git a/tests/BoxListTest.php b/tests/BoxListTest.php index 73b1ca0a..6fafbaae 100644 --- a/tests/BoxListTest.php +++ b/tests/BoxListTest.php @@ -26,4 +26,43 @@ function testCompare() { } self::assertEquals(array($box1,$box3,$box2), $sorted); } + + function testIssue14A() { + $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); + $box2 = new TestBox('Large', 1301, 1301, 1301, 1, 1300, 1300, 1300, 1000); + $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); + $list = new BoxList; + $list->insert($box1); + $list->insert($box2); + $list->insert($box3); + $sorted = []; + while (!$list->isEmpty()) { + $sorted[] = $list->extract(); + } + self::assertEquals(array($box1,$box3,$box2), $sorted); + } + + function testIssue14B() { + $box1 = new TestBox('Small', 21, 21, 3, 1, 20, 20, 2, 100); + $box2 = new TestBox('Large', 1301, 1301, 1301, 1, 1300, 1300, 1300, 1000); + $box3 = new TestBox('Medium', 101, 101, 11, 5, 100, 100, 10, 500); + $list = new BoxList; + $list->insert($box3); + $list->insert($box2); + $list->insert($box1); + $sorted = []; + while (!$list->isEmpty()) { + $sorted[] = $list->extract(); + } + self::assertEquals(array($box1,$box3,$box2), $sorted); + $list = new BoxList; + $list->insert($box2); + $list->insert($box1); + $list->insert($box3); + $sorted = []; + while (!$list->isEmpty()) { + $sorted[] = $list->extract(); + } + self::assertEquals(array($box1,$box3,$box2), $sorted); + } }