Pregunta

I am just starting to learn Unity3D javascript, this is my first try to learn, trying to copy a shuffle Objective-C code snippet i have, and I have the following code:

function Shuffle(theCardArray : Array) {
var dupeArray = new Array();
var count = theCardArray.length;

print("theCardArray: " + theCardArray);


dupeArray = theCardArray;
    count = dupeArray.length;
print("A) Count dupeArray: " + count);
print("B) Count dupeArray: " + dupeArray.length);
theCardArray.Clear();

for (var i = 0; i < count; i++) {

    // Select random element between i and the end of the array to swap it
    var nElements = count - i;
    var n = Random.Range(0, nElements);

    print("#1");
    print("C) Count dupeArray: " + dupeArray.length);
    print("dupeArray: " + dupeArray);
    var dummyString = dupeArray[n];
    print("#2");

    theCardArray.Push(dummyString);
    print("#3");
}

}

I get the following in my prints:

theCardArray: back,D2,D3,D4,D5,D6,D7,D8,D9,D10,DJ,DQ,DK

A) Count dupeArray: 13

B) Count dupeArray: 13

'#1'

C) Count dupeArray: 0

At B) the dupeArray have 13 entities and at C) the dupeArray is empty!

Could someone please explain to me why the array is empty at C)?

BTW, i know there are other ways in Unity3D to achieve the same thing but this is for learning!

The final and real solution I came up with for this is:

Call ShuffleThis with:

arr = ShuffleThis(arr);

The Shuffle function:

function ShuffleThis(theCardArray : Array) : Array {

var size : int = theCardArray.length;

for (var i : int = 0; i < size; i++) {

    var indexToSwap : int = Random.Range(i, size);
    var oldValue = theCardArray[i];
    theCardArray[i] = theCardArray[indexToSwap];
    theCardArray[indexToSwap] = oldValue;
}

return theCardArray;
}

Source: Fisher-Yates Shuffle with UnityScript

¿Fue útil?

Solución

It's because the array dupeArray is just a reference to the original array theCardArray, so when you clear the original array you are also clearing the duplicate array; by reference.

In order to resolve your issue you should clone the original array, this can be done using slice like this...

var dupeArray = theCardArray.slice(0);

Alternatively, it can also be done using the jQuery extend approach like this...

var dupeArray = $.extend(true, [], theCardArray);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top