如何在JavaScript中的两个指定变量之间生成随机整数,例如x = 4
,y = 8
并输出以下任何内容4, 5, 6, 7, 8
?
在JavaScript中生成特定范围内的随机整数?
- random(min,max) generates a random number between min (inclusive) and max (exclusive)
Math.floor rounds a number down to the nearest integer
function generateRandomInteger (min, max) { return Math.floor(random(min,max)) }`
So to generate a random integer between 4 and 8 inclusive, call the above function with the following arguments:
generateRandomInteger (4,9)
I made this function which takes into account options like min, max, exclude (a list of ints to exclude), and seed (in case you want a seeded random generator).
get_random_int = function(args={})
{
let def_args =
{
min: 0,
max: 1,
exclude: false,
seed: Math.random
}
args = Object.assign(def_args, args)
let num = Math.floor(args.seed() * (args.max - args.min + 1) + args.min)
if(args.exclude)
{
let diff = args.max - args.min
let n = num
for(let i=0; i<diff*2; i++)
{
if(args.exclude.includes(n))
{
if(n + 1 <= args.max)
{
n += 1
}
else
{
n = args.min
}
}
else
{
num = n
break
}
}
}
return num
}
It can be used like:
let n = get_random_int
(
{
min: 0,
max: some_list.length - 1,
exclude: [3, 6, 5],
seed: my_seed_function
}
)
Or more simply:
let n = get_random_int
(
{
min: 0,
max: some_list.length - 1
}
)
Then you can do:
let item = some_list[n]
Gist: https://gist.github.com/madprops/757deb000bdec25776d5036dae58ee6e
/*
Write a function called randUpTo
that accepts a number and returns a
random whole number between 0 and that number?
*/
var randUpTo = function(num) {
return Math.floor(Math.random() * (num - 1) + 0);
};
/*
Write a function called randBetween
that accepts two numbers
representing a range and returns a random whole number between those two
numbers.
*/
var randBetween = function (min, max) {
return Math.floor(Math.random() * (max - min - 1)) + min;
};
/*
Write a function called randFromTill
that accepts two numbers
representing a range and returns a random number between min (inclusive)
and max (exclusive).
*/
var randFromTill = function (min, max) {
return Math.random() * (max - min) + min;
};
/*
Write a function called randFromTo
that accepts two numbers
representing a range and returns a random integer between min (inclusive)
and max (inclusive)
*/
var randFromTo = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
This can handle generating upto 20 digit UNIQUE random number
JS
var generatedNumbers = [];
function generateRandomNumber(precision) { // precision --> number precision in integer
if (precision <= 20) {
var randomNum = Math.round(Math.random().toFixed(precision) * Math.pow(10, precision));
if (generatedNumbers.indexOf(randomNum) > -1) {
if (generatedNumbers.length == Math.pow(10, precision))
return "Generated all values with this precision";
return generateRandomNumber(precision);
} else {
generatedNumbers.push(randomNum);
return randomNum;
}
} else
return "Number Precision shoould not exceed 20";
}
generateRandomNumber(1);
You can you this code snippet,
let randomNumber = function(first,second){
let number = Math.floor(Math.random()*Math.floor(second));
while(number<first){
number = Math.floor(Math.random()*Math.floor(second));
}
return number;
}
this is my take on a random number in a range, as in I wanted to get a random number within a range of base to exponent. e.g. base = 10, exponent = 2, gives a random number from 0 to 100, ideally, and so on.
if it helps use it, here it is:
// get random number within provided base + exponent
// by Goran Biljetina --> 2012
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
var numSeq = new Array();
function add(num,seq){
var toAdd = new Object();
toAdd.num = num;
toAdd.seq = seq;
numSeq[numSeq.length] = toAdd;
}
function fillNumSeq (num,seq){
var n;
for(i=0;i<=seq;i++){
n = Math.pow(num,i);
add(n,i);
}
}
function getRandNum(base,exp){
if (isEmpty(base)){
console.log("Specify value for base parameter");
}
if (isEmpty(exp)){
console.log("Specify value for exponent parameter");
}
fillNumSeq(base,exp);
var emax;
var eseq;
var nseed;
var nspan;
emax = (numSeq.length);
eseq = Math.floor(Math.random()*emax)+1;
nseed = numSeq[eseq].num;
nspan = Math.floor((Math.random())*(Math.random()*nseed))+1;
return Math.floor(Math.random()*nspan)+1;
}
console.log(getRandNum(10,20),numSeq);
//testing:
//getRandNum(-10,20);
//console.log(getRandNum(-10,20),numSeq);
//console.log(numSeq);
To get crypto-strong random integer number in ragne [x,y] try
let rand= (x,y)=> x+(y-x+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
console.log(rand(4,8))
Here is an example of a javascript function that can generate a random number of any specified length without using Math.random():
function genRandom(length)
{
const t1 = new Date().getMilliseconds();
var min = "1",max = "9";
var result;
var numLength = length;
if (numLength != 0)
{
for (var i = 1; i < numLength; i++)
{
min = min.toString() + "0";
max = max.toString() + "9";
}
}
else
{
min = 0;
max = 0;
return;
}
for (var i = min; i <= max; i++)
{
//Empty Loop
}
const t2 = new Date().getMilliseconds();
console.log(t2);
result = ((max - min)*t1)/t2;
console.log(result);
return result;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<script>
/*
assuming that window.crypto.getRandomValues is available
the real range would be fron 0 to 1,998 instead of 0 to 2,000
See javascript documentation for explanation
https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
*/
var array = new Uint8Array(2);
window.crypto.getRandomValues(array);
console.log(array[0] + array[1]);
</script>
</body>
</html>
Uint8Array create a array filled with a number up to 3 digits which would be a maximum of 999. This code is very short.
Random whole number between lowest and highest:
function randomRange(l,h){
var range = (h-l);
var random = Math.floor(Math.random()*range);
if (random === 0){random+=1;}
return l+random;
}
Not the most elegant solution.. but something quick.
I know this question is already answered but my answer could help someone.
I found this simple method on W3Schools:
Math.floor((Math.random() * max) + min);
Hope this would help someone.
To get a random number say between 1 and 6, first do:
0.5 + (Math.random() * ((6 - 1) + 1))
This multiplies a random number by 6 and then adds 0.5 to it. Next round the number to a positive integer by doing:
Math.round(0.5 + (Math.random() * ((6 - 1) + 1))
This round the number to the nearest whole number.
Or to make it more understandable do this:
var value = 0.5 + (Math.random() * ((6 - 1) + 1))
var roll = Math.round(value);
return roll;
In general the code for doing this using variables is:
var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1))
var roll = Math.round(value);
return roll;
The reason for taking away 0.5 from the minimum value is because using the minimum value alone would allow you to get an integer that was one more than your maximum value. By taking away 0.5 from the minimum value you are essentially preventing the maximum value from being rounded up.
Hope that helps.
For a random integer with a range, try:
function random(minimum, maximum) {
var bool = true;
while (bool) {
var number = (Math.floor(Math.random() * maximum + 1) + minimum);
if (number > 20) {
bool = true;
} else {
bool = false;
}
}
return number;
}
Use this function to get random numbers between given range
function rnd(min,max){
return Math.floor(Math.random()*(max-min+1)+min );
}
Here is the MS DotNet Implementation of Random class in javascript-
var Random = (function () {
function Random(Seed) {
if (!Seed) {
Seed = this.milliseconds();
}
this.SeedArray = [];
for (var i = 0; i < 56; i++)
this.SeedArray.push(0);
var num = (Seed == -2147483648) ? 2147483647 : Math.abs(Seed);
var num2 = 161803398 - num;
this.SeedArray[55] = num2;
var num3 = 1;
for (var i_1 = 1; i_1 < 55; i_1++) {
var num4 = 21 * i_1 % 55;
this.SeedArray[num4] = num3;
num3 = num2 - num3;
if (num3 < 0) {
num3 += 2147483647;
}
num2 = this.SeedArray[num4];
}
for (var j = 1; j < 5; j++) {
for (var k = 1; k < 56; k++) {
this.SeedArray[k] -= this.SeedArray[1 + (k + 30) % 55];
if (this.SeedArray[k] < 0) {
this.SeedArray[k] += 2147483647;
}
}
}
this.inext = 0;
this.inextp = 21;
Seed = 1;
}
Random.prototype.milliseconds = function () {
var str = new Date().valueOf().toString();
return parseInt(str.substr(str.length - 6));
};
Random.prototype.InternalSample = function () {
var num = this.inext;
var num2 = this.inextp;
if (++num >= 56) {
num = 1;
}
if (++num2 >= 56) {
num2 = 1;
}
var num3 = this.SeedArray[num] - this.SeedArray[num2];
if (num3 == 2147483647) {
num3--;
}
if (num3 < 0) {
num3 += 2147483647;
}
this.SeedArray[num] = num3;
this.inext = num;
this.inextp = num2;
return num3;
};
Random.prototype.Sample = function () {
return this.InternalSample() * 4.6566128752457969E-10;
};
Random.prototype.GetSampleForLargeRange = function () {
var num = this.InternalSample();
var flag = this.InternalSample() % 2 == 0;
if (flag) {
num = -num;
}
var num2 = num;
num2 += 2147483646.0;
return num2 / 4294967293.0;
};
Random.prototype.Next = function (minValue, maxValue) {
if (!minValue && !maxValue)
return this.InternalSample();
var num = maxValue - minValue;
if (num <= 2147483647) {
return parseInt((this.Sample() * num + minValue).toFixed(0));
}
return this.GetSampleForLargeRange() * num + minValue;
};
Random.prototype.NextDouble = function () {
return this.Sample();
};
Random.prototype.NextBytes = function (buffer) {
for (var i = 0; i < buffer.length; i++) {
buffer[i] = this.InternalSample() % 256;
}
};
return Random;
}());
Use:
var r = new Random();
var nextInt = r.Next(1, 100); //returns an integer between range
var nextDbl = r.NextDouble(); //returns a random decimal
If you need variable between 0 and max you can use:
Math.floor(Math.random() * max);
Return a random number between 1 and 10:
Math.floor((Math.random()*10) + 1);
Return a random number between 1 and 100:
Math.floor((Math.random()*100) + 1)
function randomRange(min, max) {
return ~~(Math.random() * (max - min + 1)) + min
}
Alternative if you are using Underscore.js you can use
_.random(min, max)
Math.random()
从Mozilla开发人员网络文档中:
// Returns a random integer between min (include) and max (include)
Math.floor(Math.random() * (max - min + 1)) + min;
有用的例子:
// 0 - 10
Math.floor(Math.random() * 11);
// 1 - 10
Math.floor(Math.random() * 10) + 1;
// 5 - 20
Math.floor(Math.random() * 16) + 5;
// -10 - (-2)
Math.floor(Math.random() * 9) - 10;
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
My method of generating random number between 0 and n, where n <= 10 (n excluded):