Randoming the order of a list

Hi! I have a squiffy game, but I would like to randomize the order of a list.

Do I have to do that in JavaScript, or does squiffy provide some way of doing it?


I've done it but it's kinda kludgy. I'm going to wait until the JS aces come in on this. Otherwise, Ill post my solution.


Don't know about Squiffy, but in JS it's pretty easy.

    somelist = ["red", "blue", "green", "pink"];
    for (i=somelist.length ; i > 0 ; i--) {
      somelist.push (somelist.splice(Math.floor(Math.random() * i), 1)[0]);
    }

I'm not a JS stormrider by any means. This doesn't duplicate elements on the list, does it? I figure he wanted it unique.


It takes one of the first 4 elements at random (so any of them), and moves it to the end.

Then it takes one of the first 3 elements (the ones that haven't been shuffled yet) at random, and moves it to the end.

Then it takes one of the first 2 elements (the ones that haven't been shuffled yet) at random, and moves it to the end.

Gives an equal chance of every possible order, in the minimum number of movements.

Doesn't duplicate, because there's a splice for every pop.


This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums