Skip to content Skip to sidebar Skip to footer

Random Value Generation Javascript

I have some code for storing a random value from an array into a variable like this: Quest=['value1','value2','value3','value4']; var random=Math.floor( Math.random() * Quest.lengt

Solution 1:

  • Populate an array with the numbers 0 through (Quest.length-1).

  • Use this JavaScript code to shuffle that array.

Repeat:

  • For first time(t=0),output array[t].

  • For second time(t=1),output array[t].

  • when t%Quest.length (or array.length)==0.

  • Again shuffle the array.

    and Repeat.

    functionshuffle(o) 
        { 
         for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
            return o;
        };
        Quest = ["value1", "value2", "value3", "value4"];
        var myarray = newArray();
        var i = 0;
        for (i = 0; i < Quest.length; i++) {
            myarray[i] = i;
        }
        shuffle(myarray);
        for (i = 0; i < myarray.length; i++) {
            document.write(myarray[i]);
        }
        for (i = 0; i < 50; i++) {
            if (i % (Quest.length) == 0) {
                shuffle(myarray);
            }
            document.write("<p>" + Quest[myarray[i % (Quest.length)]] + "</p>");
        }
    

Solution 2:

You can do it using splice method:

varQuest = ["value1", "value2", "value3", "value4"];
var random1 = Quest.splice(Math.floor(Math.random() * Quest.length), 1)[0];
...
var random2 = Quest.splice(Math.floor(Math.random() * Quest.length), 1)[0];
... 
var random3 = Quest.splice(Math.floor(Math.random() * Quest.length), 1)[0];

Since the value is removed from the Quest array it's guaranteed that questions will never repeat

Demo: http://jsfiddle.net/dfsq/QUztw/3/

Note: if you don't want to modify the initial array you can work with its copy Quest.slice().

Solution 3:

Use Fisher-Yates to shuffle the array:

var Quest=["value1","value2","value3","value4"];

functionkfy(array)
{
  for (var i = array.length - 1; i > 0; --i) {
    var p = Math.floor(Math.random() * (i + 1)),
    tmp = array[p];
    array[p] = array[i];
    array[i] = tmp;
  }
}

console.log(Quest);
kfy(Quest);
console.log(Quest);

Then, just iterate from the beginning to the end of your array.

Solution 4:

Another possibility is to random-sort the array:

functionrandomOrder() {
 return (Math.round(Math.random())-0.5);
}

varQuest = ["value1", "value2", "value3", "value4"];
Quest.sort(randomOrder);

At that point you can walk the array and it shouldn't repeat.

Post a Comment for "Random Value Generation Javascript"