Search code examples
javascriptcrashgenetic-algorithm

My code code infinitely and crashes the page


This is my code:

// Population
var Gene = function(text){
    if(text){
        this.text = text;
    }
};

Gene.fitness = 0;
Gene.generation = 0;

var word = new Gene('Hello');

// This is where it crashes!!
// Make elements
var genArr = [];
var population = 20;
var mutation = 0;
for(var i = 0; i < population; i++){
   var gene = "";
    var abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var j = 0; i < word.text.length; j++) {
        var element = abc.charAt(Math.floor(Math.random() * abc.length));
        gene += element;
    }
    genArr.push(gene);
}

// Divide them - fitness
// 1/20 - 0.05% each
var fitElements = [];
for (var i = 0; i < genArr.length; i++) {
    var score = 0;
    var curWord = Array.from(genArr[i]);
    for (var j = 0; j < word.text.length; j++) {
        if(genArr[j].substr(j, 1) == word.text.substr(j, 1)){
            score += 1;
        }
    }
    if(score > 0){
        fitElements.push([genArr[i], (score * (1 / population)) ** 2]);
    }
}

for (var i = 0; i < fitElements.length; i++) {
    console.log('Element: ' + fitElements[i][0] + ', Score: ' + fitElements[i][1]);
}

My problem is that it crashes the page but doesn't gives errors. The idea is to create a simple word register in fitElements Array but I can't see what am I missing? Thanks in advance.


Solution

  • In your code the nested for loop with variable j's end condition relies on i. Take a the line:

    //             VVVV it relies on i instead of j
    for (var j = 0; i < word.text.length; j++) {
        var element = abc.charAt(Math.floor(Math.random() * abc.length));
        gene += element;
    }
    

    The new code would look something like

    for (var j = 0; j < word.text.length; j++) 
        var element = abc.charAt(Math.floor(Math.random() * abc.length));
        gene += element;
    }
    

    The only difference in the entire sample is the i is changed to a j. Cheers!