Generate unique random numbers between 1 and 100

2018-12-31 05:37发布

How can I generate 8, say, unique random numbers between 1 and 100 using JavaScript?

26条回答
栀子花@的思念
2楼-- · 2018-12-31 06:23

This can handle generating upto 20 digit UNIQUE random number

JS

 var generatedNumbers = [];

    function generateRandomNumber(precision) { // input --> 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-31 06:23

Another simpler approach is to generate an 100 items array with ascending numbers and sort it randomly. This leads actually to a really short and (in my opinion) simple snippet.

function randomNumbers() {
  const numbers = [ ...Array(100).keys() ].map(num => num + 1);
  numbers.sort(() => Math.random() - 0.5);
  return numbers.slice(0, 8);
}
查看更多
妖精总统
4楼-- · 2018-12-31 06:24

The above techniques are good if you want to avoid a library, but depending if you would be alright with a library, I would suggest checking out Chance for generating random stuff in JavaScript.

Specifically to solve your question, using Chance it's as easy as:

// One line!
var uniques = chance.unique(chance.natural, 8, {min: 1, max: 100});

// Print it out to the document for this snippet so we can see it in action
document.write(JSON.stringify(uniques));
<script src="http://chancejs.com/chance.min.js"></script>

Disclaimer, as the author of Chance, I am a bit biased ;)

查看更多
梦该遗忘
5楼-- · 2018-12-31 06:25

var arr = []
while(arr.length < 8){
    var r = Math.floor(Math.random()*100) + 1;
    if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);

查看更多
还给你的自由
6楼-- · 2018-12-31 06:29
  1. Populate an array with the numbers 1 through 100.
  2. Shuffle it.
  3. Take the first 8 elements of the resulting array.
查看更多
不流泪的眼
7楼-- · 2018-12-31 06:30

How about using object properties as a hash table? This way your best scenario is to only randomize 8 times. It would only be effective if you want a small part of the range of numbers. It's also much less memory intensive than Fisher-Yates because you don't have to allocate space for an array.

var ht={}, i=rands=8;
while ( i>0 || keys(ht).length<rands) ht[Math.ceil(Math.random()*100)]=i--;
alert(keys(ht));

I then found out that Object.keys(obj) is an ECMAScript 5 feature so the above is pretty much useless on the internets right now. Fear not, because I made it ECMAScript 3 compatible by adding a keys function like this.

if (typeof keys == "undefined") 
{ 
  var keys = function(obj) 
  {
    props=[];
    for (k in ht) if (ht.hasOwnProperty(k)) props.push(k);
    return props;
  }
}
查看更多
登录 后发表回答