I have come across a very strange problem. I have tried to find its solution but in vain. My problem is that I want to create a random number between 1-45 and I don't want that number to repeat again.
Asked
Active
Viewed 1,860 times
-2
-
3Take an. Array, fill it with the range of numbers, shuffle it, pop the values off – Moritz Roessler Feb 15 '13 at 06:30
-
-1. No effort. Random sampling without replacement is not at all a strange problem, it is often encountered in textbooks on programming and there are solutions online in many languages including js. If you had googled "javascript random without replacement" the first three results are from stackoverflow, the first one is http://stackoverflow.com/questions/12987719/javascript-how-to-randomly-sample-items-without-replacement . See also http://stackoverflow.com/questions/11935175/sampling-a-random-subset-from-an-array . – Paul Feb 15 '13 at 06:52
4 Answers
4
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(","));

Niet the Dark Absol
- 320,036
- 81
- 464
- 592
-
2Be wary of [randomizing arrays that way though...](http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html) – maerics Feb 15 '13 at 06:50
-
0
This is Working code..
Random rd =new Random();
int n = rd.Next(1,45);

coder
- 1,980
- 3
- 21
- 32
-
-
-
oh yes, my bad, javas random class has a `nextInt` method , mistook it for that – Moritz Roessler Feb 15 '13 at 07:46
0
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

maerics
- 151,642
- 46
- 269
- 291
-
Relies on new methods of Object.prototype. The above code fails in IE8 and below. – Niet the Dark Absol Feb 15 '13 at 06:42
0
This is working
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}

Shima
- 3
- 3