0

I am getting a random generated number between one and 10 from getRandom(1,10), but i do not want the same number twice.
To prevent that, I am saving the number I get inside an array used.

Now I want to check if the new number I get already is inside that array.
If not continue going,
if it is, then start over (get new number etc.).

What I am missing right now is the part where it should start over. Or should this work?

jQuery(document).ready(function($){

var i=0;
while (i<21){

        var used = new Array(20);
        for(a=0; a<20; a++) {
            var number = getRandom(1, 20);
            used[a] = number;
        }
        var tf = inArray(number,used);

        //Check if number is inside the 
        if(tf==false){
            //If not
            i++;

        }else{
            //If it is 
            i--;
        }
}

function inArray(Item,arr) {
    for(p=0;p<arr.length;p++) {
        if (arr[p]==Item) {
            return true;
        }
    }
    return false;
}

});
Slotty Bon
  • 101
  • 6
  • 1
    If you are using jquery, why not using jquery method $.inArray() ? – A. Wolff Jun 29 '13 at 16:40
  • 2
    You could put 1-20 in an array and sort them randomly, then draw numbers from that array from index 0, incrementing each time. There are examples in other SO questions. – Spencer Moran Jun 29 '13 at 16:42
  • Did not know jQuery could do that. – Slotty Bon Jun 29 '13 at 16:48
  • Other SO questions? Would you be so nice and post one of these methods? Or link to one of them? – Slotty Bon Jun 29 '13 at 16:51
  • http://stackoverflow.com/questions/5143401/how-to-choose-a-set-of-unique-random-numbers-no-duplicates-using-the-jquery-in. http://stackoverflow.com/questions/3796786/random-number-generator-without-dupes-in-javascript answer by JoshD – Spencer Moran Jun 29 '13 at 17:13
  • I truly hope you read, understand, and use @gonchuki's solution from http://stackoverflow.com/questions/5143401/how-to-choose-a-set-of-unique-random-numbers-no-duplicates-using-the-jquery-in. This very much is an X-Y Problem, please understand that. – 000 Jun 29 '13 at 17:53
  • alright, then it is. I think with the link from Spencer Moran will solve my problem anyway. Nevertheless, I thank you for looking at my problem. – Slotty Bon Jun 29 '13 at 18:37

1 Answers1

0
// create pool of numbers
var pool = [];
for (var i=1; i<=20; i++)
    pool.push(i);

// pop off a random element of the array
var some_random_number = pool.splice(Math.floor(Math.random()*pool.length), 1)[0]

// repeat until pool is empty.
000
  • 26,951
  • 10
  • 71
  • 101