Skip to content

Add shuffle method to ArrayUtil class #170

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/com/adobe/utils/ArrayUtil.as
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
}
}
}
}
16 changes: 16 additions & 0 deletions tests/src/com/adobe/utils/ArrayUtilTest.as
Original file line number Diff line number Diff line change
Expand Up @@ -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]));
}
}

}
}