From b01ed021eaee519c035b707cfdfb77501e32a7bb Mon Sep 17 00:00:00 2001 From: Slava Kim Date: Fri, 21 Feb 2014 17:48:22 -0800 Subject: [PATCH] New giant randomized test with self-checks --- packages/binary-heap/binary-heap-tests.js | 34 +++++++++++++++++++++++ packages/binary-heap/max-heap.js | 9 ++++++ 2 files changed, 43 insertions(+) diff --git a/packages/binary-heap/binary-heap-tests.js b/packages/binary-heap/binary-heap-tests.js index 9a709b6fe4..496af9c0c3 100644 --- a/packages/binary-heap/binary-heap-tests.js +++ b/packages/binary-heap/binary-heap-tests.js @@ -81,3 +81,37 @@ Tinytest.add("binary-heap - min-max heap tests", function (test) { test.equal(h.minElementId(), "a"); }); +Tinytest.add("binary-heap - big test for min-max-heap", function (test) { + var N = 500; + var positiveNumbers = _.shuffle(_.range(1, N + 1)); + var negativeNumbers = _.shuffle(_.range(-1, -N - 1, -1)); + var allNumbers = positiveNumbers.concat(negativeNumbers); + + var heap = new MinMaxHeap(function (a, b) { return a-b; }); + var output = []; + + _.each(allNumbers, function (n) { + heap.set(n, n); + heap._selfCheck(); + heap._minHeap._selfCheck(); + }); + + allNumbers = _.shuffle(allNumbers); + _.each(allNumbers, function (n) { + heap.set(-n, n); + heap._selfCheck(); + heap._minHeap._selfCheck(); + }); + + _.times(positiveNumbers.length + negativeNumbers.length, function () { + var minId = heap.minElementId(); + output.push(heap.get(minId)); + heap.remove(minId); + heap._selfCheck(); heap._minHeap._selfCheck(); + }); + + allNumbers.sort(function (a, b) { return a-b; }); + + test.equal(output, allNumbers); +}); + diff --git a/packages/binary-heap/max-heap.js b/packages/binary-heap/max-heap.js index 891e9b3771..2d70e3509d 100644 --- a/packages/binary-heap/max-heap.js +++ b/packages/binary-heap/max-heap.js @@ -195,6 +195,15 @@ _.extend(MaxHeap.prototype, { maxElementId: function () { var self = this; return self.size() ? self._heap[0].id : null; + }, + + _selfCheck: function () { + var self = this; + for (var i = 1; i < self._heap.length; i++) + if (self._maxIndex(parentIdx(i), i) !== parentIdx(i)) + throw new Error("An item with id " + self._heap[i].id + + " has a parent younger than him: " + + self._heap[parentIdx(i)].id); } });