+ 3
Random Numbers, every number once
Hi, i try to figure out, how i can code a function that give me 4 random numbers in a range from 1 to 20. But every random number should appeare once. e.g. If number 1 ist = 4, 4 may no longer occure
3 Answers
+ 2
if found this:
var arr = []
while(arr.length < 5){
var randomnumber = Math.floor(Math.random()*5) + 1;
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
document.write(arr);
but i dont understand it completly and would like to code it with variables like this:
var number1= Math.floor(Math.random()*5)+1;
var number2= Math.floor(Math.random()*5)+1;
var number3= Math.floor(Math.random()*5)+1;
var number4= Math.floor(Math.random()*5)+1;
var number5= Math.floor(Math.random()*5)+1;
var number6= Math.floor(Math.random()*5)+1;
document.write(number1 + " | " + number2 + " | " + number3 +" | " + number4 + " | " + number5 + "<br/><br/>");
But my problem is to find a solution for equal numbers:
do
{number1= Math.floor(Math.random()*5)+1;
} while (number1 == number2)
that seems to work for two numbers, but i cant figure out how i make it work for more than two.
+ 1
Max Mi Hi there! Try using the search bar next time to help eliminate double threads. I found some posts that may be able to help you. Check them outđ
https://www.sololearn.com/discuss/1433903/?ref=app
https://www.sololearn.com/discuss/1393927/?ref=app
https://www.sololearn.com/discuss/1258425/?ref=app
0
From my limited knowledge of JavaScript, you would need an array for more than 2 numbers. Could be weong though