如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?


当前回答

您可以使用此代码段,

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

其他回答

function getRandomInt(lower, upper)
{
    //to create an even sample distribution
    return Math.floor(lower + (Math.random() * (upper - lower + 1)));

    //to produce an uneven sample distribution
    //return Math.round(lower + (Math.random() * (upper - lower)));

    //to exclude the max value from the possible values
    //return Math.floor(lower + (Math.random() * (upper - lower)));
}

要测试此函数以及此函数的变体,请将以下HTML/JavaScript保存到文件中,然后用浏览器打开。该代码将生成一个图表,显示一百万个函数调用的分布。代码还将记录边缘事例,因此如果函数产生的值大于最大值,或小于最小值,则您将知道大约。

<html>
    <head>
        <script type="text/javascript">
        function getRandomInt(lower, upper)
        {
            //to create an even sample distribution
            return Math.floor(lower + (Math.random() * (upper - lower + 1)));

            //to produce an uneven sample distribution
            //return Math.round(lower + (Math.random() * (upper - lower)));

            //to exclude the max value from the possible values
            //return Math.floor(lower + (Math.random() * (upper - lower)));
        }

        var min = -5;
        var max = 5;

        var array = new Array();

        for(var i = 0; i <= (max - min) + 2; i++) {
          array.push(0);
        }

        for(var i = 0; i < 1000000; i++) {
            var random = getRandomInt(min, max);
            array[random - min + 1]++;
        }

        var maxSample = 0;
        for(var i = 0; i < max - min; i++) {
            maxSample = Math.max(maxSample, array[i]);
        }

        //create a bar graph to show the sample distribution
        var maxHeight = 500;
        for(var i = 0; i <= (max - min) + 2; i++) {
            var sampleHeight = (array[i]/maxSample) * maxHeight;

            document.write('<span style="display:inline-block;color:'+(sampleHeight == 0 ? 'black' : 'white')+';background-color:black;height:'+sampleHeight+'px">&nbsp;[' + (i + min - 1) + ']:&nbsp;'+array[i]+'</span>&nbsp;&nbsp;');
        }
        document.write('<hr/>');
        </script>
    </head>
    <body>

    </body>
</html>

其他答案没有考虑到0和1这两个完全合理的参数。相反,您应该使用圆形而不是天花板或地板:

function randomNumber(minimum, maximum){
    return Math.round( Math.random() * (maximum - minimum) + minimum);
}

console.log(randomNumber(0,1));  # 0 1 1 0 1 0
console.log(randomNumber(5,6));  # 5 6 6 5 5 6
console.log(randomNumber(3,-1)); # 1 3 1 -1 -1 -1

这是我对一个范围内的随机数的看法,就像我想得到一个基数到指数范围内的一个随机数。例如,基数=10,指数=2,理想情况下给出从0到100的随机数,依此类推。

如果它有助于使用它,这里是:

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

加密功能强

要获取[x,y]范围内的加密强随机整数,请尝试:

让cs=(x,y)=>x+(y-x+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0控制台日志(cs(4,8))

使用现代JavaScript+Lodash:

const generateRandomNumbers = (max, amount) => {
  const numbers = [...Array(max).keys()];
  const randomNumbers = sampleSize(numbers, amount);

  return randomNumbers.sort((a, b) => a - b);
};

此外,TypeScript版本:

const generateRandomNumbers = (max: number, amount: number) => {
  const numbers = [...Array(max).keys()];
  const randomNumbers: number[] = sampleSize(numbers, amount);

  return randomNumbers.sort((a: number, b: number) => a - b);
};