In comp.lang.javascript message <Xn********************@194.109.133.242>
, Sun, 11 Mar 2007 21:11:47, Evertjan. <ex**************@interxnl.net>
posted:
>var a = []; // array
var max = 100; // number of pics
for (var i=0;i<max;i++)
a[i]=i; // fill with numbers 0 - 99
for (var i=0;i<max*3;i++) {
n1 = Math.floor(Math.random()*max);
n2 = Math.floor(Math.random()*max);
// never mind if some swap with themselves
temp = a[n1];
a[n1] = a[n2];
a[n2] = temp; // swap the numbers at random
};
// "a" is now a reasonable random sequence array of 100 unique numbers
One can do better than that, by following a link in the FAQ.
function Deal(N) { var J, K, Q = new Array(N)
for (J=0; J<N; J++) { K = Random(J+1) ; Q[J] = Q[K] ; Q[K] = J }
return Q }
That, with minimum effort, and assuming that Math.random is perfect,
generates any of the possible sequences with exactly equal probability;
yours does not give exactly equal probability, only very nearly so, and
takes longer. Note that Random(1) is used.
But the OP does not want all of that array; there is no need to
randomise the order of the unwanted elements.
function PickSubsetSequenced(Q, M) { var J, K, L = Q.length, T
for ( K = L ; K L-M ; K-- ) { J = Random(K)
T = Q[K-1] ; Q[K-1] = Q[J] ; Q[J] = T }
return Q.slice(L-M) }
The OP probably wants the first 8 images to be chosen at random, but
different; and to be replaced after an interval by another 8 similarly
chosen but perhaps required to be different. Alternatively, after
loading the first 8 "instantly", the replacements might occur one at a
time or in rapid sequence.
By using the method of "Indefinite Random Slide Show" and writing in
turn to each of the 8 positions in order at appropriately-varying
intervals including nominal zero[*], many likely possibilities can be
achieved (including making changes at random intervals).
var J = 0, Delay = [10,10,10,10,10,10,10,3000]
function Go() { // untested
Image[J] = next-one
setTimeout("Go()", Delay[J]
J = (J+1)%8 }
Random sequences should not be generated with a method chosen at random;
they should be generated by a method chosen from Knuth.
[*] Has any difficulty been reported with setTimeout(xxx, 0) ? If so,
use a delay of say 10.
It's a good idea to read the newsgroup and its FAQ. See below.
--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 6
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.