0

I need to generate an unique random number for my .each() loop. Here is my function for generating the random numbers:

function GenerateRandomNumber(min, max) {
    var random = Math.floor(Math.random() * (max - min + 1)) + min;
    return random;
}

Here is my .each().

jQuery.each(P, function (key, value) {
    var rand = GenerateRandomNumber(0, posProduct.length);

    switch (rand) {
        case 0:
            content[2] = P[key].getSquarePro();
            posProduct.splice(posProduct[rand], 1);
            countContent.splice(2, 1);
            alert('1');
            break;
        case 1:
            content[3] = P[key].getSquarePro();
            posProduct.splice(posProduct[rand], 1);
            countContent.splice(3, 1);
            alert('2');
            break;....
    }
    console.log(content, 'content produit')
});

I don't now how to do that. I could have done a for while but I can't fix a maximum (P.length is not fixed ..) Thanks all!

MackieeE
  • 11,751
  • 4
  • 39
  • 56
lovis91
  • 1,988
  • 2
  • 14
  • 24

1 Answers1

0

Depending on the range of possible values the easiest way to generate unique random numbers is to generate an array containing all the possible values, shuffle that arrray, then loop through the array using the values within.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • Yes but shaking could return the same numbers ? It's seems to me to not be a real solution.. – lovis91 Jun 11 '14 at 14:37
  • There is only a finite number of combinations so you will always get the possibility of a repeat. Randomness includes repeats. – Tim B Jun 11 '14 at 14:38