8
I made a lottery system in order to learn, I will not post the entire code here just the part I’m stuck.
The PC draw is a sequence of 6 numbers that I present in the DOM (that doesn’t matter), so I want the first two numbers to NEVER be equal.
I tried it with While but it’s not working, look:
//gera o sorteio de 6 numeros de 1 a 20
var rn1 = 1 + (Math.round(Math.random() * 19));
var rn2 = 1 + (Math.round(Math.random() * 19));
var rn3 = 1 + (Math.round(Math.random() * 19));
var rn4 = 1 + (Math.round(Math.random() * 19));
var rn5 = 1 + (Math.round(Math.random() * 19));
var rn6 = 1 + (Math.round(Math.random() * 19));
//eis oq eu tentei
if(rn2 == rn1){ // se rn1 = rn2
while(rn2 == rn1){ // comece o loop
gerarnew1 = 1 + (Math.round(Math.random() * 19)); // gera um novo valor de 1 a 20 e roda até que...
if(gerarnew1 != rn1){ // ...não seja mais = rn1
rn2 = gerarnew1; // entao atribuo esse novo numero a rn2
break; // paro o loop e, pela logica rn2 agora é != rn1
}
}
}
//entao sao armazenados aqui e apresentados dps no resto do codigo
var rsorteio = new Array(rn1,rn2,rn3,rn4,rn5,rn6);
But as I’m posting here it’s certainly because it didn’t work, I run the algorithm several times and one hour it appears with the first two numbers equal.
What am I doing wrong?
Suggest I post the entire code?
Dude, really weird. Can you create a jsfiddle? Something else, you can simplify your code that checks for repetitions
while (rn1 === rn2) { rn2 = 1 + (Math.round(Math.random() * 19)); }
– Anthony Accioly
Can you accept any of the answers?
– Maniero