Want to produce random numbers between 1-45 without repetition

给你一囗甜甜゛ 提交于 2019-12-02 13:34:21

Random selection, by definition, will repeat randomly.

However, you can build an array containing each of your numbers and then shuffle the array, producing a random order of numbers without repetition.

var nums = [], i;
for( i=1; i<=45; i++) nums.push(i);
nums.sort(function(a,b) {return Math.random()-0.5;});
alert(nums.join(","));

This is Working code..

Random rd =new Random();    
int n = rd.Next(1,45);

What you really want is to create a set of numbers in a given range and to randomly remove one of the numbers until the set is empty.

Here is a function which generates another function which does exactly that:

function generateRandomRangeSet(beg, end) {
  var numbers = []; // Create an array in range [beg, end].
  for (var i=beg; i<=end; i++) { numbers.push(i); }
  return function() {
    if (numbers.length < 1) { throw new Error('no more numbers'); }
    var i=Math.floor(Math.random()*numbers.length), number=numbers[i];
    numbers.splice(i, 1); // Return and remove a random element of the array.
    return number;
  }
}

var r = generateRandomRangeSet(1, 45);
r(); // => 9
r(); // => 24
r(); // => 7 ... for each number [1, 45] then ...
r(); // Error: no more numbers

This is working

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!