Home > Blockchain >  how to generate two numbers between 0 and 4 in javascript, but make sure the numbers aren't the
how to generate two numbers between 0 and 4 in javascript, but make sure the numbers aren't the

Time:10-03

I'm trying to generate two numbers between 0 and 4 in javascript, but I don't want the two numbers to be the same. Any thoughts?

currently working with

state.blue_id = Math.floor(Math.random()*5);
state.red_id = Math.floor(Math.random()*5);
if(state.blue_id == state.red_id){
        ???????
    }

CodePudding user response:

Have you considered using while?

while (state.blue_id === state.red_id) {
    state.blue_id = Math.floor(Math.random()*5);
    state.red_id = Math.floor(Math.random()*5);
}

CodePudding user response:

"Rejection" is the standard way to handle this:

state.blue_id = Math.floor(Math.random()*5);
state.red_id = Math.floor(Math.random()*5);
while(state.blue_id == state.red_id){
        state.red_id = Math.floor(Math.random()*5);
    }

  • Related