I made a shuffle for arrays
in
Share your Work
•
1 year ago
I made a shuffle for arrays
// shuffle array
int[] a = new int[3];
// int[] a2 = new int[3];
//
void setup() {
for (int i=0; i<a.length; i++) {
a[i] = i+1;
}
println("the intial array: ");
display(a); //displays 1 2 3
println("----------------------");
println("randomized array: ");
randomize(a);
/*the second display method can display either
1 2 3 or
1 3 2 or
2 1 3 or
2 3 1 or
3 1 2 or
3 2 1
*/
}
//
void draw() {
if (keyPressed) {
randomize(a);
}
}
//
//method for display
void display(int[] arr) {
for (int i=0; i<arr.length; i++)
print(arr[i]+" ");
println();
}
//
//method for randomizing
void randomize (int[] a) {
for (int k=0; k < a.length; k++) {
// Goal: swap the value at pos k with a rnd value at pos x.
// save current value from pos/index k into temp
int temp = a[k];
// make rnd index x
int x = (int)random(0, a.length);
// overwrite value at current pos k with value at rnd index x
a[k]=a[x];
// finish swapping by giving the old value at pos k to the
// pos x.
a[x]=temp;
}
display(a);
}