/ Published in: Other
Expand |
Embed | Plain Text
static public function shuffle(orgArray:Array):Array{ var newArray = new Array(); while (orgArray.length>0){ newArray.push(orgArray.splice(randomRange(0,orgArray.length), 1)); } return newArray; } static public function randomRange(min:Number,max:Number){ if(min==null)min=Number.NEGATIVE_INFINITY; if(max==null)max=Number.POSITIVE_INFINITY; return Math.floor(Math.random()*(max-min)+min) }
Comments
Subscribe to comments
You need to login to post a comment.

This is a fast version of the Fisher-Yates shuffle. It will work well for small arrays. Array length: time(ms) 0: 0 100: 8 200: 34 300: 66 400: 114 500: 183 600: 275 700: 356 800: 510 900: 619 1000: 821
Sorry, I retract my earlier post. The shuffle above is not good, because it takes a long time. The shuffle below completes the task more than 10x faster. It can complete shuffle of a 10,000 item array (I used Math.random to fill each element) in 100 ms, while the shuffle above will take more than 15 seconds. The key here is to switch places, not to copy and recopy the array using splice and push.
I think there's a minor glitch in your script in line 6:
I guess
orgArray[_iterator] = orgArray[random, 1];Ought to be:
orgArray[_iterator] = orgArray[random];Furthermore, I think methods like the following are nice to extend classes, like:
Array.prototype.shuffle = function():Void { var iterator:Number, _length:Number = this.length, temp; for (iterator = 0; iterator < _length; _iterator++){ temp = this[iterator]; newIndex = randomRange(iterator,this.length); this[iterator] = this[newIndex]; this[newIndex] = temp; } }function randomRange(min:Number,max:Number):Number{ if(min==null)min=Number.NEGATIVEINFINITY; if(max==null)max=Number.POSITIVEINFINITY; return Math.floor(Math.random()*(max-min)+min) }
Now the original array can be shuffled like :
myArray.shuffle();(I removed the temporary keyword variable 'random' to use the value from the array directly).
Hope this helps.
Wow, how can I clean my mess up? Though markdown would use my code-tags like the black text above (aside from my unclosed code tag in block two)