-1

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

0

5 Answers 5

2

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])

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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));

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.