I recently needed to shuffle the contents of an array and end up with a randomly sorted or shuffled result. After doing some research and looking at examples of others I noticed that there are several ways to achieve the same goal, but there are clear performance advantages to some methods. Below is an example based off of inspiration of others and what I developed as a test for a commercial project. This example is compatible with both AS2 and AS3.
var input:Array = ["item1", "item2", "item3", "item4", "item5"]; var output:Array = new Array(); function shuffle():Array { while(input.length > 0) { var n:Number = Math.floor(Math.random() * input.length); output.push(input[n]); input.splice(n, 1); } return output; } shuffle();
Download the .fla for fully-commented example.
0 Responses to “Shuffling an Array”
Leave a Reply