How to generate random numbers from the given numbers [duplicate] - javascript

This question already has answers here:
Get a random item from a JavaScript array [duplicate]
(13 answers)
Getting a random value from a JavaScript array
(28 answers)
Closed 3 years ago.
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 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));

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.

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.

Related

How to make a function that is stateless determistic random unique number generator? [duplicate]

This question already has answers here:
Seedable JavaScript random number generator
(11 answers)
Seeding the random number generator in Javascript
(20 answers)
Closed 24 days ago.
Here is a function that will generate a Random set of numbers that are unique from a range:
function randUniqueRange(quantity, max){
const set = new Set()
while(set.size < quantity) {
set.add(Math.floor(Math.random() * max) + 1)
}
return set
}
console.log(randUniqueRange(6, 20)) // randome set { 6,3,4,5,9,7 }
Question: How can I add a 3rd argument called seed. Seed will ensure that the output created will be determinist given the same arguements aka the order + selected numbers will always be the same if given the same arguements
Example:
function randUniqueRange(quantity, max, seed){
const set = new Set()
while(set.size < quantity) {
set.add(Math.floor(Math.random() * max) + 1)
}
return set
}
console.log(randUniqueRange(3, 20, 'a')) // {1,2,5}
console.log(randUniqueRange(3, 20, 1)) // {2,1,10}
console.log(randUniqueRange(3, 20, 'a')) // {1,2,5}

How to get a random number from an Array without repetition in Javascript? [duplicate]

This question already has answers here:
Generating non-repeating random numbers in JS
(20 answers)
Closed 3 years ago.
I am trying to return a random number from an array of numbers i.e. cardNumbertemp.
function cardRandomiser(){
randomCard = Math.floor(Math.random()*cardNumbertemp.length);
for (var i = 0; i < cardNumbertemp.length; i++){
if (randomCard === cardNumbertemp[i]){
cardNumbertemp.splice(i,1);
return randomCard;
}
}
}
This function needs to return a single random number from the array (cardNumbertemp) then remove the number from the array. It works however sometimes it returns undefined.
If you are looking to getting a random number, you can use the below code. You ideally need not splice unless you do not intend to have that number again.
var cardNumbertemp = [45, 78, 23, 89];
(function() {
console.log(getRandom());
})();
function getRandom() {
randomCard = Math.floor(Math.random() * cardNumbertemp.length);
return cardNumbertemp[randomCard];
}
let cardNumbertemp = [45, 78, 23, 89];
for(let i = 0; i < cardNumbertemp.length + i; i++){
// will give you random number b/w 0 & (length of given array - 1)
let randomIndex = Math.floor((Math.random() * cardNumbertemp.length));
console.log(cardNumbertemp[randomIndex]); // output random array value
cardNumbertemp.splice(randomIndex, 1); // maintain unique random value
}

Recursion in a while loop in javascript

I try to output randomly some numbers from an array of possible values.
The problem that I have is with the recursion, so that my function checking if the number generated randomly was already used before starts again if the number was already used (and is not in the array of possible values anymore).
I get an infinite loop which I also don't understand.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
// Global array of possible numbers
var possibleNumbers = [1, 2, 3, 4];
// Check if element in the array
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
// Random number between 1 and 4
function genRand(){return Math.floor(1+ (4 * Math.random()));}
// Return an random number from the possible numbers in the global array
function randNumFromArray() {
var generatedNum = genRand();
console.log('possibleNumbers so far:' + possibleNumbers);
console.log('generatedNum: ' + generatedNum);
// Restart as long as the number is not in the array (not already used)
while(inArray(generatedNum,possibleNumbers) === false) {
console.log('Generating again...');
randNumFromArray();
}
console.log('generatedNum not used yet, using it');
// Use that number and remove it from the array
var index = possibleNumbers.indexOf(generatedNum);
if (index > -1) {
possibleNumbers.splice(index, 1);
}
console.log('Removing the number from the array');
console.log('possibleNumbers after removal:' + possibleNumbers);
return generatedNum;
}
// Calling the function 4 times to get the 4 possible numbers in a random order
randNumFromArray();
randNumFromArray();
randNumFromArray();
randNumFromArray();
</script>
</head>
<body>
</body>
</html>
Lets debug your code,
Math.random() // Returns a random number between 0 (inclusive) and 1 (exclusive)
4 * Math.random() // will be number either be 0 or 4 < number < 5.
1+ (4 * Math.random()) // In your Case you are probably waiting for Math.random() to generate 0 which of least probability (because any number other than zero will make the total sum to 5.xx)
Math.floor(1+ (4 * Math.random()) // will surely not be in your list [1, 2, 3, 4]; if number generate > 0 then will cross 4 so It will loop continuously
If you want to generate random number of specific range then use,
/**
* Returns a random number between min and max
*/
function getRandomArbitary (min, max) {
return Math.random() * (max - min) + min;
}
Refer for generating random number of specific range

Two random numbers [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate random between 0 - 9 but not 6
var ifanse=Math.floor(Math.random()*4)+1;
var ifanse2=Math.floor(Math.random()*3)+1
These are 2 random numbers. Sometimes they come equal, but is there any way if ifanse come equal to ifanse2, it will regenerate a random between 3 - 1 but exclusive of ifanse2. Or is there any way to avoid equaling at first place?
You could loop until you pick a different number:
var ifanse=Math.floor(Math.random()*4)+1;
var ifanse2=Math.floor(Math.random()*3)+1;
while (ifanse2 == ifanse)
{
ifanse2=Math.floor(Math.random()*3)+1;
}
You could for example write a generic function which gives you an array of random numbers
Filling and Array with the Numbers of your range Which will eliminate duplicate numbers
shuffling the Array
return an Array of the lenght, with the count of random Numbers you want
function genRand(min, max, cnt) {
var arr = [];
for (var i = min, j = 0; i <= max; j++, i++)
arr[j] = i
arr.sort(function () {
return Math.floor((Math.random() * 3) - 1)
});
return arr.splice(0, cnt)
}
console.log(genRand(0, 3, 2)) // e.g [0,3]
Then you could just store them in your var, or access them directly from rands
var rands = genRand(0,3,2);
var ifanse = rands[0]
var ifanse2 = rands[1]
You would never get 2 equal Numbers with this and you can generate more then 2 different rands if you ever need to.
Heres a Jsbin

How to pick a random number in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript: Getting random value from an array
I have a list of ten items.
ar = [112,32,56,234,67,23,231,123,12]
How do I choose an item randomly with javascript?
var ar = [112,32,56,234,67,23,231,123,12];
var randomKey = Math.floor(Math.random() * ar.length);
var randomValue = ar[randomKey];
Check out the documentation on the Math object; https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math
You could easily abstract this into a nice function:
function getRandom(array, getVal) {
var key = Math.floor(Math.random() * array.length);
if (getVal) {
return array[key];
}
return key;
}
Then you'd call it like getRandom(ar) to get a random key in the array, and getRandom(ar, true) to return a random value in the array.
well something like
var randnum = Math.floor ( Math.random() * ar.length );
val random = (ar[randnum]);

Categories

Resources