-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);
  • 1
    do you just need a shuffle? – Daniel A. White Sep 18 '13 at 12:35
  • 1
    Hi, please always remember to Google first. The first result when searching for `how to generate random number with no repeat same number again using javascript?` should answer your question. – Pekka Sep 18 '13 at 12:36
  • @DanielA.White is correct - put the numbers 1, 2, and 3 in an array, then shuffle the array. – Pointy Sep 18 '13 at 12:36

3 Answers3

0
  1. create an array with all numbers in sequence
  2. shuffle the array into a random order like described in the question How can I shuffle an array?
  3. iterate the array.
Community
  • 1
  • 1
Philipp
  • 67,764
  • 9
  • 118
  • 153
  • Actually this is way better way of doing it than what I suggested. 1+ for not causing unnecessary checks having to take place. – BenM Sep 18 '13 at 12:38
  • 1
    You can just randomly select a member of the array, no need to shuffle, something like `arr.splice(Math.random()*arr.length|0,1)`. – RobG Sep 18 '13 at 12:49
0

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]));
RobG
  • 142,382
  • 31
  • 172
  • 209
-1

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>
Community
  • 1
  • 1
OneOfOne
  • 95,033
  • 20
  • 184
  • 185