I am working on a generic algorithm, I have a population and a function to calculate distance. The problem comes in when I call calcDistance(population[i]) in a for loop, it turns into an infinity loop. But when using dev tool to manually input each "i", there are no problem. Please Help
// points is an array of point store in another JS file
var totalPoints;
var bestdistance = Infinity;
var bestorder;
var totalPopulation = 5;
var population = [];
var fitness = []
function btnClick() {
var canvas = document.getElementById("myCanvas");
canvas.removeEventListener('click', trackClicker);
totalPoints = points.length;
var order = [];
for (i=0; i<totalPoints; i++) {
order[i] = i;
}
for (i=0; i<totalPopulation; i++) {
population[i] = shuffle(order.slice());
}
console.log(population);
// problem
for (i=0; i<totalPopulation; i++) {
console.log(calcDistance(population[i]));
}
console.log(fitness);
}
function shuffle(arr) {
// not important
}
function calcDistance(arr) {
var d = 0;
for (i=0; i<totalPoints-1; i++) {
var p1 = points[arr[i]];
var p2 = points[arr[i+1]];
d += Math.sqrt(Math.pow(p2.x-p1.x,2) + Math.pow(p2.y-p1.y,2));
}
if (d < bestdistance) {
bestdistance = d;
bestorder = arr.slice();
}
return d;
}
WARNING: The snippet below is an infinite loop and will crash your browser. It has also been slightly modified from the above so it runs in the snippet.
var totalPoints;
var bestdistance = Infinity;
var bestorder;
var totalPopulation = 5;
var population = [];
var fitness = []
let points = [{
x: 1,
y: 1
},
{
x: 2,
y: 2
},
{
x: 3,
y: 3
}
]
function btnClick() {
totalPoints = points.length;
var order = [];
for (i = 0; i < totalPoints; i++) {
order[i] = i;
}
// problem
for (i = 0; i < totalPopulation; i++) {
console.log(calcDistance(population[i]));
}
console.log(fitness);
}
function calcDistance(arr) {
var d = 0;
for (i = 0; i < totalPoints - 1; i++) {
var p1 = points[i];
var p2 = points[i + 1];
d += Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
if (d < bestdistance) {
bestdistance = d;
}
return d;
}
//temp
btnClick();
console.log(fitness);won't log anything at this point as it is empty.ilocal by declaring it withfor (var i = ...?