user7195739
user7195739

Reputation:

Incorrect random number - Javascript

I am trying to take random username and password from an array, and checking whether current username password is same as previous username password. If it is same, i want to take different user id, pass from the array. I wrote below code, but I it also picks up same username passwords.

let usernames = ["uname1", "uname2"],
        passwords = ["pass1", "pass1"];

    let rand, prevRand;
    prevRand = _.random(0, usernames.length - 1);
    rand = _.random(0, usernames.length - 1);

    console.log("rand " + rand)
    console.log("prevrand " + prevRand)


    if (rand !== prevRand) {
        console.log("uname!==: " + usernames[rand])
        console.log("pass!==: " + passwords[rand])
        prevRand = rand;
    } else {
        while (rand !== prevRand) {
            rand = _.random(0, usernames.length - 1);
            console.log("newrand " + rand)

        }
        prevRand = rand;
        console.log("unamenew " + usernames[rand])
        console.log("passnew " + passwords[rand])

    }

Please correct my logic here..Thanks.

Upvotes: 1

Views: 90

Answers (2)

Hristo93
Hristo93

Reputation: 197

rand === prevRand is true in the else case, so it will never enter the while cycle.

The cycle, instead, must loop while rand is equal to prevRand

  while (rand === prevRand) {
        rand = _.random(0, usernames.length - 1);
        console.log("newrand " + rand)
 }

Each time they are equal a new value to rand should be given, so they can be different.

Upvotes: 0

Kirill Simonov
Kirill Simonov

Reputation: 8481

Your while (rand !== prevRand) loop is never executed because it is inside the else statement wich means that rand == prevRand. Try changing the while loop to do..while.

Check the example (I've replaced _.random with Math.random to run without external libraries)

let usernames = ["uname1", "uname2", "uname3", "uname4"],
    passwords = ["passw1", "passw2", "passw3", "passw4"];

let rand, prevRand;
prevRand = Math.floor(Math.random() * (usernames.length));
rand = Math.floor(Math.random() * (usernames.length));

console.log("rand " + rand)
console.log("prevrand " + prevRand)


if (rand !== prevRand) {
    console.log("uname " + usernames[rand])
    console.log("pass " + passwords[rand])
    prevRand = rand;
} else {
    do {
        rand = Math.floor(Math.random() * (usernames.length));
        console.log("newrand " + rand)
    } while (rand == prevRand);
    prevRand = rand;
    console.log("unamenew " + usernames[rand])
    console.log("passnew " + passwords[rand])
}

Upvotes: 1

Related Questions