is there a better way to randomize an array like the following one?
theArray = randomizeArray(theArray);
function randomizeArray(arr : Array) : Array
{
var counter : int = arr.length;
var reArr = new Array();
while (counter-- >= 1)
{
var rndM : int = Random.Range(0, arr.length-1);
reArr.push(arr[rndM]);
arr.RemoveAt(rndM);
}
return reArr;
}
Here's a slightly simpler version which doesn't create a new array, or add/remove elements to the array. It simply swaps elements around in the original array, giving a very fast algorithm which is useful if this happens to be part of some speed-critical code. (this is called the Fisher Yates shuffle).
static function RandomizeArray(arr : Array)
{
for (var i = arr.length - 1; i > 0; i--) {
var r = Random.Range(0,i);
var tmp = arr*;*
_arr *= arr[r];*_
_*arr[r] = tmp;*_
_*}*_
_*}*_
_*```*_
_*<p>Because this works on the original array, it does not return a result. To use, you would simply call:</p>*_
_*```*_
_*RandomizeArray(myArray);*_
_*```*_
<em>*<p>In addition, because this function doesn't rely on adding or removing items, it can also be adapted to work with <strong><a href="http://www.unifycommunity.com/wiki/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use?#Built-in_Arrays" rel="nofollow">built-in arrays</a></strong> rather than <a href="http://unity3d.com/support/documentation/ScriptReference/Array.html" rel="nofollow">Unity's <strong>Javascript Arrays</strong></a> by simply changing the input parameter type to <strong>Object[]</strong> rather than <strong>Array</strong>, and by writing ".length" as ".Length" (change the lower case l to a capital L). Eg:</p>*</em>
_*```*_
_*static function RandomizeBuiltinArray(arr : Object[])*_
_*{*_
_*for (var i = arr.Length - 1; i > 0; i--) {*_
_*var r = Random.Range(0,i);*_
<em>_var tmp = arr*;*_</em>
<em><em>_arr *= arr[r];*_</em></em>
<em><em>_*arr[r] = tmp;*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*}*_</em></em>
<em><em>_*```*_</em></em>
static function RandomizeArray(arr : Array){
var thisarray = new Array(arr);
var temp = Array();
for (var i = arr.Count - 1; i >= 0; i--) {
var r = Random.Range(0,i+1);
temp.Add(thisarray[r]);
thisarray.RemoveAt(r);
}
for (i = 0; i < arr.Count; i++) {
arr _= temp*;*_