View Single Post
Old 02-14-2013, 03:32 PM   PM User | #7
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,033
Thanks: 197
Thanked 2,410 Times in 2,388 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by felgall View Post
The following code worked for me when I tested it. Refreshing the page enough times eventually gets all the values to display and although there was a bias toward 1 & 2 for a while it evened out as I refreshed more times.
I do not detect any bias. It worked perfectly on my tests.


Code:
<form>
<select id="s1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</form>


<script type="text/javascript">
var select= document.getElementById('s1');
for (var i=0; i<100; i++)  {
select.selectedIndex= Math.floor(Math.random() * select.options.length);
document.write(select.selectedIndex);  // 5315010225244432352211311100014220342110000244505414220343411410140314440031503010011014450553550305 
}
</script>
Be aware that random implies that the same number may be generated 2,3 or possibly even more times in succession, especially with a small number (6) of values.
Another approach would be to shuffle the numbers 1-6 into a random order, and then pick the next one in sequence, thus avoiding consecutive
appearances of the same number.

Code:
<script type = "text/javascript">

Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1));
while (s.length) this.push(s.pop());
return this;
}

var count = 0;
var arr = [1, 2, 3, 4, 5, 6];
var sarr = arr.shuffle);
document.write(sarr);  // for testing

function shownext() {
alert (sarr[count]);  // for testing
count ++;
if (count >5) {count = 0};  // start the sequence again
select.selectedIndex = count;
}
</script>
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 02-14-2013 at 04:09 PM..
Philip M is offline   Reply With Quote