Reputation: 290
I'm trying to shuffle the rows in my current array in Processing. This array contains 24 rows and is a two-dimensional-array. Can someone tell me what I do wrong?
float[][] shuffleArray(float[][] myArray) {
float[][] newArray = myArray;
int random1 = round(random(0, 24));
int random2 = round(random(0, 24));
float[] buffer1 = newArray[random1];
float[] buffer2 = newArray[random2];
newArray[random2] = buffer1;
newArray[random1] = buffer2;
return newArray;
}
Upvotes: 0
Views: 419
Reputation: 42176
To fix your problem, you first have to debug your program to figure out exactly what your program does.
The best thing to do is to go through your code line by line to understand what's happening.
float[][] shuffleArray(float[][] myArray) {
float[][] newArray = myArray;
int random1 = round(random(0, 24));
int random2 = round(random(0, 24));
float[] buffer1 = newArray[random1];
float[] buffer2 = newArray[random2];
newArray[random2] = buffer1;
newArray[random1] = buffer2;
return newArray;
}
First, you point a newArray
variable to the myArray
variable. Note that this means that both variables point to the same array, so changes to one will affect the other.
Then you create two random numbers, but note that those random numbers might be the same.
Then you get the sub-array at those indexes, which again might be the same. Then you swap the sub-arrays.
Then you return newArray
, but remember that this is pointing to the same array that myArray
is. So you're just modifying the input array and then returning a reference to it.
So, what this function does is maybe swap two sub-arrays in your 2D array. This is not the same as shuffling the whole array. Picture taking a deck of cards and maybe swapping two of the cards. That's not the same thing as shuffling the whole deck.
To understand references, I recommend you read this and then this.
Now, to fix your problem, Google is your friend. Searching for "java shuffle array" will return a ton of results, including this and this. If you have problems in the future, please try to work through this process of debugging your program so you understand exactly what your code is doing before you ask a question. Good luck.
Upvotes: 1