I am trying to use a priority Queue for my own data type which is a 3x3 array. The actual code and data type is more complex so I boiled it down to the essentials. Note that the priority queue works well for an integer data type (see output at the end). Everything is self explanatory. Assume the metric function returns a positive integer for a given 3X3 array. I am confused why the dequeueing from the heap does not return the min valued object (or max valued in case I got the comparator backwards but I got the middle value for both). For the data type of integer the priority Queue seems to work correctly as the output shows.
var r = require('js-priority-queue');
metric = function (A) {
N = A.length;
if (A[0][1] == 0) return 123;
if (A[0][1] == 5) return 124;
if (A[0][1] == 1) return 122;
if (A[0][1] == 6) return 122;
return 0;
}
mComparator = function (m1, m2) {
ret = metric(m2) - metric(m1);
return ret;
}
mHeap = new r(mComparator);
nHeap = new r(function (a,b) {
return b - a;
})
A = [[5, 0, 1], [7, 6, 3], [2, 4, 8]];
B = [[5, 6, 1], [7, 0, 3], [2, 4, 8]];
C = [[5, 1, 0], [7, 6, 3], [2, 4, 8]];
D = [[0, 5, 1], [7, 6, 3], [2, 4, 8]];
console.log("metric(A) -> %d", metric(A));
console.log("metric(B) -> %d", metric(B));
console.log("metric(C) -> %d", metric(C));
console.log("metric(D) -> %d", metric(D));
mHeap.queue(A);
mHeap.queue(B);
mHeap.queue(C);
mHeap.queue(D);
X = mHeap.dequeue();
console.log(X);
X = mHeap.dequeue();
console.log(X);
X = mHeap.dequeue();
console.log(X);
X = mHeap.dequeue();
console.log(X);
nHeap.queue(123);
nHeap.queue(124);
nHeap.queue(122);
nHeap.queue(122);
y = nHeap.dequeue();
console.log(y);
#Output
metric(A) -> 123
metric(B) -> 122
metric(C) -> 122
metric(D) -> 124
[ [ 5, 0, 1 ], [ 7, 6, 3 ], [ 2, 4, 8 ] ]
[ [ 0, 5, 1 ], [ 7, 6, 3 ], [ 2, 4, 8 ] ]
[ [ 5, 1, 0 ], [ 7, 6, 3 ], [ 2, 4, 8 ] ]
[ [ 5, 6, 1 ], [ 7, 0, 3 ], [ 2, 4, 8 ] ]
122
js-priority-queueimplementation and themetriccomparison function, aren't shown?