Permalink
Browse files

Add shuffle method to ArrayUtil class.

  • Loading branch information...
1 parent 24c6c16 commit b0b5fd5df0585ba920ba60f9bb9830eec499e3ba @endel committed Jun 26, 2011
Showing with 43 additions and 1 deletion.
  1. +27 −1 src/com/adobe/utils/ArrayUtil.as
  2. +16 −0 tests/src/com/adobe/utils/ArrayUtilTest.as
View
28 src/com/adobe/utils/ArrayUtil.as
@@ -153,7 +153,7 @@ package com.adobe.utils
* Compares two arrays and returns a boolean indicating whether the arrays
* contain the same values at the same indexes.
*
- * @param arr1 The first array that will be compared to the second.
+ * @param arr1 The first array that will be compared to the second.
*
* @param arr2 The second array that will be compared to the first.
*
@@ -183,5 +183,31 @@ package com.adobe.utils
return true;
}
+
+ /**
+ * Shuffle the indexes of source array
+ *
+ * @param source The source array to shuffle items
+ *
+ * @param startIndex [optional] Array index that shuffle will start
+ *
+ * @param endIndex [optional] Array index that shuffle will end
+ *
+ * @langversion ActionScript 3.0
+ * @playerversion Flash 9.0
+ * @tiptext
+ */
+ public static function shuffle(source:Array,startIndex:int = 0, endIndex:int = 0) : void
+ {
+ if (endIndex == 0)
+ endIndex = source.length-1;
+ for (var i:int = endIndex; i>startIndex; i--)
+ {
+ var randomNumber:int = Math.floor(Math.random()*endIndex)+startIndex;
+ var tmp:* = source[i];
+ source[i] = source[randomNumber];
+ source[randomNumber] = tmp;
+ }
+ }
}
}
View
16 tests/src/com/adobe/utils/ArrayUtilTest.as
@@ -168,6 +168,22 @@ package com.adobe.utils
assertTrue("!ArrayUtil.arrayContainsValue(arr, 10)",
!ArrayUtil.arrayContainsValue(arr, 10));
}
+
+ public function testArrayShuffle():void
+ {
+ var arr2:Array = ArrayUtil.copyArray(arr);
+ var length:uint = arr2.length;
+
+ ArrayUtil.shuffle(arr);
+ assertNotNull("arr is null", arr);
+ assertTrue("arr.length == arr2.length", arr.length == arr2.length);
+
+ var i : uint;
+ for (i=0;i<length;i++)
+ {
+ assertTrue("arr2["+i+"] contains in arr[]", ArrayUtil.arrayContainsValue(arr, arr2[i]));
+ }
+ }
}
}

0 comments on commit b0b5fd5

Please sign in to comment.