Mangofett Mangofett - 4 months ago 10
Javascript Question

Javascript Random Name Guesser: Unresponsive Script Issues

This is my first post here and I am having trouble wording a question, so please bear with me as I have been on this issue for hours.

My friend and I have thought of a fun little function that is supposed to guess the user's name (through an

<input>
tag) in a certain amount of trials using the random number function to access string letters from an alphabet array numbered 0-25. The function is also supposed to give the user the number of trials it took to guess their name.

I keep getting a non-responsive script, (line 33 - The line containing the second "for loop").

var goal = document.getElementById("your_Name").value;
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var goalArray = goal.split("");
var trials = 0;
var guessArray = new Array();
var i;
var n;

for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}

while (goalArray != guessArray){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + guessArray + " trials to guess correctly";


Any help or attempt to help would be immensely appreciated!

In case anyone was wondering: This little idea of ours was to test the randomness of Javascript's random function through trials (he made the same program in MatLab, so we are going to compare results of the random functions from both languages).

Answer

goalArray != guessArray is always true since they are two separate arrays; even if they contain the same elements.

Since they appear to just be arrays of individual letters in a-z you could compare them with something like goalArray + '' != guessArray, because the toString() of the arrays will compare correctly.

Comments