Generating random whole numbers in JavaScript in a specific range
There are some examples on the Mozilla Developer Network page:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Here's the logic behind it. It's a simple rule of three:
Math.random()
returns a Number
between 0 (inclusive) and 1 (exclusive). So we have an interval like this:
[0 .................................... 1)
Now, we'd like a number between min
(inclusive) and max
(exclusive):
[0 .................................... 1)
[min .................................. max)
We can use the Math.random
to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min
from the second interval:
[0 .................................... 1)
[min - min ............................ max - min)
This gives:
[0 .................................... 1)
[0 .................................... max - min)
We may now apply Math.random
and then calculate the correspondent. Let's choose a random number:
Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)
So, in order to find x
, we would do:
x = Math.random() * (max - min);
Don't forget to add min
back, so that we get a number in the [min, max) interval:
x = Math.random() * (max - min) + min;
That was the first function from MDN. The second one, returns an integer between min
and max
, both inclusive.
Now for getting integers, you could use round
, ceil
or floor
.
You could use Math.round(Math.random() * (max - min)) + min
, this however gives a non-even distribution. Both, min
and max
only have approximately half the chance to roll:
min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max
With max
excluded from the interval, it has an even less chance to roll than min
.
With Math.floor(Math.random() * (max - min +1)) + min
you have a perfectly even distribution.
min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max
You can't use ceil()
and -1
in that equation because max
now had a slightly less chance to roll, but you can roll the (unwanted) min-1
result too.
Generate random numbers within specific range and with given conditions in javascript - times table
I think this is what you are looking for. I took a completely different approach.
First, I'm using a Map because it is simple to ensure uniqueness. (keys must be unique)
Note I'm using a simple string for the key to ensure they are unique (using objects there get's a bit more complicated)
The ranges
array represents your 'number2, number3` etc.
The loop starts at 2
to satisfy your multiplier range (2 - 11). This requires a bit of trickery to get index cone correctly.
This generates unique pairs (as key) and the value of the map is the generated value and the multiplier multiplied together.
The size and Map are printed in the console.
const randomNumbersGenerator = () => {
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
const randomNumber = () => getRandomInt(2, 12);
const multiplierMap = new Map();
const ranges = [[0, 2], [0, 3], [0, 3], [0, 3], [0, 3], [1, 4], [1, 4], [1, 4], [1, 4], [0, 2], [0, 3]];
while(multiplierMap.size < 17) {
for (let i = 2; i < ranges.length+1; i++) {
const randomInt = randomNumber();
if(Array.from(multiplierMap.values).includes(randomInt * i)){
--i;
} else {
multiplierMap.set(randomInt + " " + i, randomInt * i);
}
if(multiplierMap.size === 18) break;
}
}
console.log('MultiplierMap size: ', multiplierMap.size);
for(let [pair, multiple] of multiplierMap){
console.log('Generated Multiplier: ' + pair, '||', 'Generated * Multiplier: ' + multiple);
}
return multiplierMap;
};
randomNumbersGenerator();
How to generate n random numbers within a range matching a fixed sum in javascript?
Here is one way to achieve the desired result.
The original solution is this: https://stackoverflow.com/a/19278621/17175441 which I have modified to account for the numbers range limit.
Note that there are probably better ways to do this but this does the job for now:
function generate({
targetSum,
numberCount,
minNum,
maxNum
}) {
var r = []
var currsum = 0
for (var i = 0; i < numberCount; i++) {
r[i] = Math.random() * (maxNum - minNum) + minNum
currsum += r[i]
}
let clamped = 0
let currentIndex = 0
while (currsum !== targetSum && clamped < numberCount) {
let currNum = r[currentIndex]
if (currNum == minNum || currNum == maxNum) {
currentIndex++
if (currentIndex > numberCount - 1) currentIndex = 0
continue
}
currNum += (targetSum - currsum) / 3
if (currNum <= minNum) {
r[currentIndex] = minNum + Math.random()
clamped++
} else if (currNum >= maxNum) {
r[currentIndex] = maxNum - Math.random()
clamped++
} else {
r[currentIndex] = currNum
}
currsum = r.reduce((p, c) => p + c)
currentIndex++
if (currentIndex > numberCount - 1) currentIndex = 0
}
if (currsum !== targetSum) {
console.log(`\nTargetSum: ${targetSum} can't be reached with the given options`)
}
return r
}
const numbers = generate({
targetSum: 88.3,
numberCount: 12,
minNum: 6,
maxNum: 9.99,
})
console.log('number = ', numbers)
console.log(
'Sum = ',
numbers.reduce((p, c) => p + c)
)
Generate random number between two numbers in JavaScript
Important
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
const rndInt = Math.floor(Math.random() * 6) + 1
console.log(rndInt)
Generating unique random numbers (integers) between 0 and 'x'
Use the basic Math
methods:
Math.random()
returns a random number between 0 and 1 (including 0, excluding 1).- Multiply this number by the highest desired number (e.g. 10)
Round this number downward to its nearest integer
Math.floor(Math.random()*10) + 1
Example:
//Example, including customisable intervals [lower_bound, upper_bound)
var limit = 10,
amount = 3,
lower_bound = 1,
upper_bound = 10,
unique_random_numbers = [];
if (amount > limit) limit = amount; //Infinite loop if you want more unique
//Natural numbers than exist in a
// given range
while (unique_random_numbers.length < limit) {
var random_number = Math.floor(Math.random()*(upper_bound - lower_bound) + lower_bound);
if (unique_random_numbers.indexOf(random_number) == -1) {
// Yay! new random number
unique_random_numbers.push( random_number );
}
}
// unique_random_numbers is an array containing 3 unique numbers in the given range
In Javascript generate a random whole number excluding array of numbers
Consider building an array that includes the range except for the numbers in the array. If that array is 0 elements long, you have no options yet. Then, you can pick a random index of the array.
function randomInt(min, max, exclude) {
const nums = [];
for (let i = min; i <= max; i++) {
if (!exclude.includes(i)) nums.push(i);
}
if (nums.length === 0) return false;
const randomIndex = Math.floor(Math.random() * nums.length);
return nums[randomIndex];
}
console.log(randomInt(1, 5, [2, 3]))
Generate unique random numbers between 1 and 100
For example: To generate 8 unique random numbers and store them to an array, you can simply do this:
var arr = [];
while(arr.length < 8){
var r = Math.floor(Math.random() * 100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
Generate random integer rounded to nearest whole number
This sould get the job done
Math.round((Math.floor(Math.random() * max) + min) / 10) * 10
Related Topics
Convert Form Data to JavaScript Object With Jquery
Ecmascript 6 Arrow Function That Returns an Object
Convert a JavaScript String in Dot Notation into an Object Reference
How to Access React Instance (This) Inside Event Handler
How to Pass Props to {This.Props.Children}
How to Print a Circular Structure in a Json-Like Format
Difference Between ( For... in ) and ( For... of ) Statements
Programmatically Navigate Using React-Router
Google Maps Js API V3 - Simple Multiple Marker Example
How to Convert a String to an Integer in JavaScript
Does Es6 Introduce a Well-Defined Order of Enumeration For Object Properties
Difference Between a Function Call and Function Reference
Facebook Js Sdk'S Fb.API('/Me') Method Doesn't Return the Fields I Expect in Graph API V2.4+
How to Parse CSV Data With JavaScript
"Uncaught Syntaxerror: Cannot Use Import Statement Outside a Module" When Importing Ecmascript 6