Total Pageviews

Thursday 16 June 2011

AS3 Shuffle Array

Shuffling an array is something that is always needed. Whether it is for a card game, creating a random label , or just to randomize part of your data to make your application more interesting. Shuffling in AS3 is like the following: 

package 
{
    import flash.display.*;
   
    public class Shuffling extends MovieClip
    {
        private var my_array:Array=["a","b","c","d","e","f","1","2","3","4","array","Flash"];
       
        public function Shuffling()
        {
            // constructor code
            trace("Before Shuffling: "+my_array);
            arrayShuffle(my_array);
            trace("After Shuffling: "+my_array);
        }
       
        public  function arrayShuffle(array_arr:Array):Array
        {
           for(var i:Number = 0; i < array_arr.length; i++)
           {
              var randomNum_num = Math.floor(Math.random() * array_arr.length)
              var arrayIndex = array_arr[i];
              array_arr[i] = array_arr[randomNum_num];
              array_arr[randomNum_num] = arrayIndex;
           }
           return array_arr;
        }    }   
}
First off it creates a variable of a random number between 0 and one less than the length of the array. The reason it is one less than the length of the array, is because we have Math.floor pushing the number to the "floor". It then creates a variable equal to "i" or the iteration of  loop.It then makes the index of the array to be the value of the array’s index at the random number we created. And then just the opposite, it makes the index of the array at our random number to be the value of the array at our iteration. For instance, the first iteration of the loop is 0, and if our random number is 5, then it would swap those indices, so my_array[0] would now be 5, and my_array[5] would now be 0.It continues to do this throughout the loop. Because it does not exclude indices it has already swapped, it will continue to swap out those it chooses, making the array completely random each time it is ran. After the  loop finishes, it then returns the array. we can display it by tracing an array.

No comments:

Post a Comment

Microsoft Logo using flexbox and Reactjs

 <!DOCTYPE html> <html> <head>     <script src="https://unpkg.com/react@18/umd/react.development.js" crossori...