Array.prototype.shuffle (AS3)

Posted on Oct 18, 2009 in Actionscript, Blog, Code | 0 comments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Array.prototype.shuffle = function() {
    var randomizedArr:Array = new Array();  
    var numElementsLeft:int = this.length;
 
    while (numElementsLeft) {
        var index:int = Math.floor(Math.random() * numElementsLeft);
        randomizedArr.push(this[index]);
        this.splice(index, 1);
        numElementsLeft--;
    }
   
    for (var i:int=0; i<randomizedArr.length; i++)
        this[i] = randomizedArr[i];
}
Read More

Function: Array.shuffle()

Posted on Sep 22, 2006 in Actionscript, Code | 0 comments

Helper function to randomize the contents of an array. The last ASSetPropFlags() line was recommended to me from a chap from Macromedia. For some reason defining this array as a prototype function was causing one of my arrays to be automatically shuffled when the Flash movie was created. That line prevents it from happening.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// helper function to randomize the contents of an array
Array.prototype.shuffle = function()
{
 var randomizedArr = new Array();
 numElementsLeft   = this.length;

 while (numElementsLeft)
 {
 // randomly pick an index
 index = Math.floor(Math.random() * numElementsLeft);

 // add the contents of this index to randomizedArray
 randomizedArr.push(this[index]);
 
 // remove it from original array
 this.splice(index, 1);
 
 numElementsLeft--;
 }
 
 // now update 'this' array
 for (i=0; i<randomizedArr.length; i++)
 this[i] = randomizedArr[i];
}

ASSetPropFlags(Array.prototype, "shuffle", 1, true);
Read More

Function: Array.contains()

Posted on Aug 29, 2006 in Actionscript, Code, JavaScript | 4 comments

A prototype function for finding out if an array contains an element. Works for both JS and Actionscript.

1
2
3
4
5
6
7
8
9
Array.prototype.contains = function(value)
{
  for (var i=0; i<this.length; i++)
  {
    if (this[i] == value)
      return true;
  }
  return false;
}
Read More