Posted By

cessnajumpin on 03/31/09


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

MacEvelly
hejaaa


Unique Random Array


 / Published in: ActionScript 3
 

Just uses the sort function to randomize an array

  1. var originalArray:Array = new Array("alpha", "bravo", "charlie", "delta", "echo", "foxtrot");
  2. var shuffledArray:Array = originalArray.sort(shuffle);
  3. trace(shuffledArray);
  4.  
  5. function shuffle(originalArray,shuffledArray):int
  6. {
  7. var sortNum : int = Math.round(Math.random() * 2) - 1;
  8. return sortNum;
  9. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: macumba on August 19, 2009

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.

Posted By: cessnajumpin on August 27, 2009

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.

Posted By: theHuston on July 24, 2010

Ha ha, this code looks and sounds like Jack M. Hows NY?

Posted By: GillesL on February 20, 2011

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; }); }

var count:Array = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]];
var tmp:Array;
for (var i=0; i
Posted By: GillesL on February 20, 2011

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/

You need to login to post a comment.