Generating random whole numbers in JavaScript in a

2018-12-30 23:21发布

How can I generate a random whole number between two specified variables in Javascript, e.g. x = 4 and y = 8 would output any of 4, 5, 6, 7, 8?

26条回答
残风、尘缘若梦
2楼-- · 2018-12-30 23:46

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

enter image description here

JsFiddle

查看更多
一个人的天荒地老
3楼-- · 2018-12-30 23:47

Alternate Solution :-

let makeGuess = function(guess){
    let min = 1;
    let max = 5;   
    let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min

    return guess === randomNumber;

}
console.log(makeGuess(1));
查看更多
公子世无双
4楼-- · 2018-12-30 23:49

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.

查看更多
梦寄多情
5楼-- · 2018-12-30 23:49

I got wondering how the distribution after enough runs would be for such a randomizer function.

And also to check if that distribution would be more-or-less the same in the different browsers.

So here's a snippet to run. The numbers can be changed before pressing the button.

function getRandomNumberInRange(Min, Max) {
    return Math.floor(Math.random() * (Max - Min + 1)) + Min;
}

function printDictAsTable(dict){
   let htmlstr = "<table border=1><tr><th>Number</th><th>Count</th></tr>";
   
   let sortedKeys = Object.keys(dict).sort(function(a,b){return a-b});

   for (let i=0; i<sortedKeys.length; i++) {
     let key = sortedKeys[i];
     htmlstr += "<tr><td>"+ key +" </td><td>" + dict[key] + " </td></tr>";
   }
   htmlstr += "</table>";
   document.getElementById("tableContainer").innerHTML = htmlstr;
}

function loopRandomAndPrint(){
    let min = Number(document.getElementById("randomMinLimit").value);
    let max = Number(document.getElementById("randomMaxLimit").value);
    if (max < min){let temp = max; max = min; min = temp;}
    let loopTotal = Number(document.getElementById("loopLimit").value);
    let dict = {};
    
    for(i = min; i <= max; ++i){
        dict[i] = 0;
    }

    for(i = 0; i < loopTotal; i++){
        let num = getRandomNumberInRange(min, max);
        dict[num] = dict[num] + 1;
    }
    
    printDictAsTable(dict);
}

loopRandomAndPrint();
<div id="topContainer">
<div id="inputAndButton" style="float: left;">
<p>Min  : <input type="number" id="randomMinLimit" value=4></p>
<p>Max  : <input type="number" id="randomMaxLimit" value=8></p>
<p>Loops: <input type="number" id="loopLimit" value=1000></p>
<button type="button" onclick="loopRandomAndPrint()">
Loop random function and show </button>
</div>
<div id="tableContainer" style="float: right;">
</div>
</div>

查看更多
有味是清欢
6楼-- · 2018-12-30 23:50

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.

查看更多
浅入江南
7楼-- · 2018-12-30 23:50

Here's what I use to generate random numbers.

function random(high,low) {
    high++;
    return Math.floor((Math.random())*(high-low))+low;
}

We do execute high++ becauseMath.random() generates a random number between 0, (inclusive), and 1(exclusive) The one being excluded, means we must increase the high by one before executing any math. We then subtract low from high, giving us the highest number to generate - low, then +low, bringing high back to normal, and making the lowest number atleast low. then we return the resulting number

random(7,3) could return 3,4,5,6, or 7

查看更多
登录 后发表回答