how to generate random number 1 to 3 with no repeat same number again. ths is my code:
function randomFromInterval(from,to)
{
var rancalue=Math.floor(Math.random()*(to-from+1)+from);
return rancalue;
}
var rannumber=randomFromInterval(1,3);
how to generate random number 1 to 3 with no repeat same number again. ths is my code:
function randomFromInterval(from,to)
{
var rancalue=Math.floor(Math.random()*(to-from+1)+from);
return rancalue;
}
var rannumber=randomFromInterval(1,3);
If you don't mind destroying the array, you can splice a random member from the array:
var getOne = (function(arr) {
return function() {
return arr.splice(Math.random()*arr.length|0,1);
};
}([1,2,3]));
If you want to start again once you've run out of numbers, then keep the original array and copy it each time the spliced array runs out of members:
var getOne = (function(original) {
var arr = [];
return function() {
if (!arr.length) arr = original.concat();
return arr.splice(Math.random()*arr.length|0,1);
};
}([1,2,3]));
Using the shuffle function from here :
<script>
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var random_generator = function(to, from) {
var nums = [];
for(var i = to; i <= from; ++i) nums.push(i);
return function() {
if(nums.length === 0) return null;
return shuffle(nums).pop();
}
}
var rand_unique_range = random_generator(10, 100), num;
while((num = rand_unique_range()) !== null) console.log(num)
</script>