Randomize an Array

/ Published in: ActionScript 3
Save to your folder(s)

<p>To randomize an array we loop over the length of the array, removing an object chosen at random and then adding it back onto the Array's end position. Think of this as having a deck of cards where you pick a card at random from the deck and move it to the top of the stack repeated for the total number of cards in the deck. It's important to note that the splice method returns an Array containing the removed object and not the object itself hence adding the [0] after the splice call to reference the contained object.</p>

Copy this code and paste it in your HTML
  1. for (var i:uint = 0; i < myArray.length; i++)
  2. {
  3. var rand:uint = int(Math.random() * myArray.length);
  4. myArray.push( myArray.splice( rand, 1 )[0] );
  5. }

URL: http://enva.to/e4ig6z

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.