JRS: In article <MP************************@news-server.nc.rr.com>,

seen in news:comp.lang.javascript, Dan Brussee <dbrussee@NOTbetterwaycom

puting.com> posted at Mon, 30 Jun 2003 01:06:41 :-

In article <be**************************@posting.google.com >,

je***********@yahoo.ca says... Hello--

I would like to display a different line of text (32 different

messages) on refresh, BUT with no repeats.

Think of this is a sort of card shuffling routine. You have 32 cards and

want them randomized. Obviously, not duplicates.

A common way of doing this in gaming is to take the array of cards and

just mix up their values. Then go through the array one at a time as if

they were NOT shuffled. Psuedo-code follows:

var a;

var b;

var tmp;

for (var y = 0; y < 10; y++) { // repeat shuffle y times

for (var x = 0; x < 32; x++) {

a = math.random(32); // cant remember the method here... sorry.

b = math.random(32);

tmp = ary(a);

ary(a) = ary(b);

ary(b) = tmp;

}

}

for (var x = 0; x < 32; x++) {

document.write("Item " + x + ": " + ary(x) + "<br/>");

}

Pseudo.

Good idea, bad algorithm. See FAQ 4.22, both for

function Random(x) { return Math.floor(x*Math.random()) }

// generates random integer in 0 .. x-1

and for a link to efficient dealing and shuffling.

For N items, there are N! possible orders, so for a good shuffle the

operation must have [a multiple of] N! possible outcomes, all equi-

probable. For this it is both necessary and sufficient to call

Random(N) ... Random(2 or 1).

With, therefore, a little subtlety in your x loop, the y loop is not

needed.

function Shuffle(Q) { var R, T, J

for (J=Q.length-1 ; J>0 ; J--)

{ R=Random(J+1) ; T=Q[J] ; Q[J]=Q[R] ; Q[R]=T }

return Q }

--

© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MSIE 4 ©

<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript

<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.

<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.