所以,我们的教授要求用JavaScript做一个蛮力旅行推销员,这是我使用的排列算法:
function heapPermute(A, callback){
var n = A.length;
var c = [];
var i = 0;
for(i = 0; i < n; i++){
c[i] = 0;
}
callback(A);
i = 0;
while(i < n){
if(c[i] < i){
if(i % 2){
swap(A, c[i], i);
}else{
swap(A, 0, i);
}
callback(A);
c[i]++;
i = 0;
}else{
c[i] = 0;
i++;
}
}
}
并称之为:
heapPermute(ArrayOfIndex, function(input){
console.log(input);
});
使用ArrayOfIndex = [1,2,3]
的控制台输出Array [ 0, 1, 2 ]
Array [ 1, 0, 2 ]
Array [ 2, 0, 1 ]
Array [ 0, 2, 1 ]
Array [ 1, 2, 0 ]
Array [ 2, 1, 0 ]
事情是,当我使用简单的回调函数,如console.log()时,代码运行没有问题,控制台记录所有排列,但如果我尝试使用索引来计算最佳路径,我在访问时得到Undefined数组位置。
bestDistance = Number.MAX_SAFE_INTEGER;
distMatrix = //Matrix read from .json;
bestRoute = [];
function checkIfBestRoute(route){
console.log(route); //this prints an Array with 2 undefined positions
//distMatrix is global
var distance = distMatrix[route[route.length - 1]][route[0]]; //Undefined route[0]
for(var i = 0; i < route.length - 1; i++){
distance += distMatrix[route[i]][route[i + 1]];
}
if(distance < bestDistance){
bestDistance = distance;
bestRoute = route.splice(0);
}
}
heapPermute(ArrayOfIndex, checkIfBestRoute); //Undefined route[0] trace
使用ArrayOfIndex = [0,1,2,3]
调用上述块时的控制台输出Array [ 0, 1, 2, 3 ]
Array [ undefined, undefined ]
TypeError: route[0] is undefined