New giant randomized test with self-checks

This commit is contained in:
Slava Kim
2014-02-21 17:48:22 -08:00
parent 74553efa30
commit b01ed021ea
2 changed files with 43 additions and 0 deletions

View File

@@ -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);
});

View File

@@ -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);
}
});