/ Published in: ActionScript 3
Just uses the sort function to randomize an array
Expand |
Embed | Plain Text
var originalArray:Array = new Array("alpha", "bravo", "charlie", "delta", "echo", "foxtrot"); var shuffledArray:Array = originalArray.sort(shuffle); trace(shuffledArray); function shuffle(originalArray,shuffledArray):int { var sortNum : int = Math.round(Math.random() * 2) - 1; return sortNum; }
Comments
Subscribe to comments
You need to login to post a comment.

If I understand this code correctly, it is quite broken. It is not even guaranteed to finish at all. The shuffle function does not, as specified in the contract in the documentation, return whether element "originalArray" should come before or after "shuffledArray," but will return something different even when called with the same parameter. (The parameter names are confusing since they are not arrays, but strings.) Since the implementation of the sort algorithm hasn't been specified by Adobe, it might be calling the shuffle function repeatedly for the same two values, getting different results, and getting the sort algorithm into a state of confusion (I just move "c" before "g" and now it's telling me it's the other way around again?!?)
Anyway, don't use this.
Hahaha......wow.
You may want to take another look there. Shuffle does nothing other than return a -1,0, or 1 to be used with the sort function (and that function is well documented by Adobe, probably because it's one of theirs). Amazingly, arrays can contain strings! I know it's a simple concept, but can understand how that could be confusing.
Anyways, there's nothing wrong with my code.
Ha ha, this code looks and sounds like Jack M. Hows NY?
This function works but one should know that it doesn't produce an even randomization. In the exemple above, the array length is 6, so each item should have a probability of 1/6 to be found at any place in the randomized result. It's not the case. Here is a little test I built to convince myself :
function shuffle($a:Array):Array { return $a.sort( function ($a,$b):int { var sortNum : int = Math.round(Math.random() * 2) - 1; return sortNum; }); }OK comments are too short for my explanation so here's the conclusion : don't use this function if you want an even randomization of your array. I wrote a snippet for the full explanation: http://snipplr.com/view/49292/beware-with-array-shuffle-function/