-1

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){
        ???????
    }
Rowan_B
  • 13
  • 1
  • 1
    Create an array [0,1,2,3,4]. Then use `splice` to remove a random number from the array: `state.blue_id = yourArray.splice(Math.random() * yourArray.length, 1);` Repeat – 001 Oct 02 '21 at 12:37
  • 1
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Oct 02 '21 at 13:03

2 Answers2

0

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);
}
esqew
  • 42,425
  • 27
  • 92
  • 132
  • Why does this no-effort question deserve an answer? And why haven't you closed it as a duplicate of one of the many "unique random numbers" question? – Andreas Oct 02 '21 at 13:03
0

"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);
    }
RBarryYoung
  • 55,398
  • 14
  • 96
  • 137
  • Why does this no-effort question deserve an answer? And why haven't you closed it as a duplicate of one of the many "unique random numbers" question? – Andreas Oct 02 '21 at 13:03