Generating random numbers on different input texts and ensuring random numbers shown are unique

StackOverflow https://stackoverflow.com/questions/23401012

Domanda

I'm trying to create a JavaScript code segment with JQuery which has random numbers that are constantly changing and will show in different text boxes.

However, I can't figure out how to make the numbers show different values for each text box. How can I accomplish this?

Here is my JavaScript code so far:

var pcount = $(".pcount");
for(var i= 0; i < pcount.length; i++){
var n = []; 
var element = pcount.eq(i);
setInterval(function() {
    n[i] = 10 + Math.floor(Math.random(Number($( ".pcount" ).val())) * 10);    
    $('.pcount').val(n[i]); 
}, 1000);}

Here is the HTML code for the text boxes:

<input type="text" class="pcount pc1" value="10"/>
<input type="text" class="pcount pc2" value="13"/>
<input type="text" class="pcount pc3" value="16"/>
È stato utile?

Soluzione

To make sure the random numbers are truly unique, you have to keep track of all random numbers that came before and if you get a conflict, generate a new one:

var makeUniqueRandom = (function() {
    var randoms = {};
    return function(low, hi) {
        var rand;
        while (true) {
            rand = Math.floor((Math.random() * (hi - low)) + low);
            if (!randoms[rand]) {
                randoms[rand] = true;
                return rand;
            }
        }
    }
})();

Usage:

var rand = makeUniqueRandom(1, 10);

Notes: You have to make absolutely sure you don't exhaust the available random numbers because if you do, it will turn into an infinite loop. So, if you're asking for random numbers from 1-10 (9 possible values), then don't call it more than 9 times.


To put random values into <input> tags, you can do this:

<input type="text" class="pcount pc1" value="10"/>
<input type="text" class="pcount pc2" value="13"/>
<input type="text" class="pcount pc3" value="16"/>

$(".pcount").each(function() {
    this.value = makeUniqueRandom(1, 10);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top