...

View Full Version : How to do Random pick from array with no repeat...



mazdaspring
09-05-2010, 08:55 PM
My array contains 15 value I want to random pick 5 value:


myArray[0] ="a";
myArray[1] ="b";
myArray[2] ="c";
myArray[3] ="d";
myArray[4] ="e";
myArray[5] ="f";
myArray[6] ="g";
myArray[7] ="h";
myArray[8] ="i";
myArray[9] ="j";
myArray[10] ="k";
myArray[11] ="l";
myArray[12] ="a";
myArray[13] ="b";
myArray[14] ="c";




How to random pick from all elements with no repeat of the same content.
e.g. if myArray[0] is picked then myArray[12] will not be picked again. (because they have the same value "a")

jimhill
09-05-2010, 09:12 PM
My array contains 15 value I want to random pick 5 value:


myArray[0] ="a";
myArray[1] ="b";
myArray[2] ="c";
myArray[3] ="d";
myArray[4] ="e";
myArray[5] ="f";
myArray[6] ="g";
myArray[7] ="h";
myArray[8] ="i";
myArray[9] ="j";
myArray[10] ="k";
myArray[11] ="l";
myArray[12] ="a";
myArray[13] ="b";
myArray[14] ="c";




How to random pick from all elements with no repeat of the same content.
e.g. if myArray[0] is picked then myArray[12] will not be picked again. (because they have the same value "a")

If you are able to write the basic javascript, in the loop concantenate the results into a string then check the string for a repeat prior to adding a new character. Let me know if you dont understand and I will code it for you.

rnd me
09-05-2010, 10:06 PM
simply shuffle the array and use [].pop() to draw one index at a from the top; you'll never repeat.





//define array:
myArray=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "a", "b", "c"];

//shuffle array:
myArray.sort(function(){return Math.round(Math.random());});


//show 5 picks from shuffled array:
alert( [
myArray.pop(),
myArray.pop(),
myArray.pop(),
myArray.pop(),
myArray.pop()
]);

Philip M
09-05-2010, 11:36 PM
Try this as an alternative to rnd me's neat solution:-



<script type = "text/javascript">
var myArray = [];
myArray[0] ="a"; // I assume these are phrases or sentences, not just letters
myArray[1] ="b";
myArray[2] ="c";
myArray[3] ="d";
myArray[4] ="e";
myArray[5] ="f";
myArray[6] ="g";
myArray[7] ="h";
myArray[8] ="i";
myArray[9] ="j";
myArray[10] ="k";
myArray[11] ="l";
myArray[12] ="a";
myArray[13] ="b";
myArray[14] ="c";

var len = myArray.length;
var chosen = [];

for (var i = 0; i<=4; i++) {
var randy = Math.floor(Math.random() * len);
chosen[i] = myArray[randy];

for (k=0; k<=i-1; k++) {
if (chosen[k] == chosen[i]) {
i--; // duplicate found so decrement i
}
}
}

alert (chosen);

</script>

Quizmaster: What is the more common name given to the aurora borealis?
Contestant: Hmm, I'm not really a plant person.

mazdaspring
09-07-2010, 11:17 PM
Thank you so much. It works really well.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum