@UKHeliBob offers a good solution for scrambling ten items.
It is clear what you are doing, and easy to see why it works.
When/if you get to scrambling a larger number of items, it's time to take a page from the book you didn't write and use the Fisher-Yates shuffle algorithm.
It is harder to see what's happening. I can figure it out one day, but the next I cannot write it down on a blank piece of paper, which means I haven't been able to understand it very well. Or my brain is mush. Both I guess.
What Fisher-Yayes has going for it is that it will only need N random numbers to shuffle N items. The simple shuffle would need many more than N to get a good shuffle when N is large-ish. Dunno where large in that context is and would depend also on how much time you had to get the job done.
# define N 52
int array[N];
void shuffle()
{
int i, j, tmp;
for (i = N - 1; i > 0; i--) {
j = random(i + 1);
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
I even manage to forget all about it, but the matter comes up not infrequently around here, see this recent thread for your amusement:
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
size_t arraySize = sizeof array / sizeof * array;
void printArray() {
for (size_t i = 0; i < arraySize; ++i) {
Serial.print(array[i]);
Serial.write(' ');
}
Serial.println();
}
void fisherYatesShuffle() {
// Start from the last element and swap it with a randomly selected element before it
for (int i = arraySize - 1; i > 0; --i) {
// Generate a random index between 0 and i (inclusive)
int randomIndex = random(0, i + 1);
// Swap array[i] with the randomly selected element
int temp = array[i];
array[i] = array[randomIndex];
array[randomIndex] = temp;
}
}
void setup() {
Serial.begin(115200);
// create a bit of randomness
randomSeed(analogRead(A0));
Serial.println(F("Before shuffling"));
printArray();
// shuffle the array
fisherYatesShuffle();
Serial.println(F("After shuffling"));
printArray();
}
void loop() {}