I have an scenario to generate random numbers that should generate from the given numbers.
for example, I have an array num=[23,56,12,22]. so i have to get random number from the array
I have an scenario to generate random numbers that should generate from the given numbers.
for example, I have an array num=[23,56,12,22]. so i have to get random number from the array
You can do something like this:
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
let num=[23,56,12,22];
let randomPosition = getRandomInt(num.length);
console.log(num[randomPosition])
You can make a function that returns a random integer between 0 and the length of the array, like this:
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
Then call it, like this:
let randomInt = getRandonInt(lengthOfArray);
console.log(randomInt);
Expected output: 0, 1, 2 .. length of array
Then just simply use the randomInt to get whatever you need from your array entries.
you can generate a random index between 0
and array.length - 1
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getRandomIntFromArray(array) {
return array[getRandomInt(array.length)]
}
const num = [23,56,12,22]
getRandomIntFromArray(num)
Use Math.floor(Math.random() * x)
, where x is the length of the Array to generate a random number between 0 and the max index
const data = [23,56,12,22]
function randomIndex (array) {
return array[Math.floor(Math.random() * array.length)];
}
console.log(randomIndex(data));
How about drawing a uniform distributed random integer in the interval [0,len(num)-1]
which represents the index of the number you draw from your array num
.
This is a very simple and straight forward approach.