Reputation: 111
I know, TL;DR - please bear with me.
This Javascript function is supposed to take in two strings inputted by the user (username, password), guess both fields correctly using the random function to generate random character guesses (out 92 characters) that are stored in two "guess arrays," and also tell how many times (trials) it took to guess both your username and password in the same instance by comparing the values of two sets of two arrays: the guess array for the username vs the user inputted array for the username, and the guess array for the password vs the user inputted array for the password.
The main line of code I'm having trouble with:
while (userNameArray != userNameGuessArray && passwordArray != passwordGuessArray){
Normally (without the second set of arrays), I would handle this situation by nesting the "while loop" in a "for loop" like so:
for (x = 0; x < userNameArray.length; x++){
while (userNameArray[x] != userNameGuessArray[x]){
Only problem is that this time I need to check another set of arrays in addition to the first set of arrays.
My question is:
If not with "!=" or with the above code, how does one check if two arrays don't share the exact same variables?
var username = document.getElementById("your_Username").value;
var userNameArray = username.split("");
var userNameGuessArray = [];
var password = document.getElementById("your_Password").value;
var passwordArray = password.split("");
var passwordGuessArray = [];
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","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","0","1","2","3","4","5","6","7","8","9","`","~","!","@","#","$","%","^","&",
"*","(",")","[","]","{","}","_","-","|","\\","'",'"',",",".",":",";","<",">","/","?"];
var trials = 0;
while (userNameArray != userNameGuessArray && passwordArray != passwordGuessArray){
trials++;
userNameGuessArray = [];
passwordGuessArray = [];
for (z = 0; z < userNameArray.length; z++){
userNameGuessArray.push(alphabet[Math.floor(Math.random()*92)]);
}
for (y = 0; y < passwordArray.length; y++){
passwordGuessArray.push(alphabet[Math.floor(Math.random()*92)]);
}
}
Any help would be greatly appreciated!
Upvotes: 1
Views: 110
Reputation: 1416
You can write a helper function that checks if the arrays are equal. See this post for such a function.
Then you can say:
while(!arrayEqual(arr1, arr2) && !arrayEqual(arr3, arr4))
EDIT:
You should read up on refactoring, which is a method of breaking of reorganising code into simpler, reusable, units.
Refactoring is what we did here. Checking that arrays are equal is not dependant on the functionality of your program, so we can break it off into it's own function. This reduces the code in your existing function, improves readability, and allows other parts of your code to reuse the arrayEqual
function.
Upvotes: 1