# define N 13 // # to shuffle 1 .. N
byte array[N];
char buffer[80];
void setup() {
Serial.begin(115200);
Serial.println("\hi Mom!");
pinMode(2, INPUT_PULLUP);
randomSeed(0xb4dc0de);
// init once only
for (byte ii = 0; ii < N; ii++) array[ii] = N - 1 - ii; // just for fun
printArray();
}
void loop() {
topInAtRandom();
printArray();
delay(300);
while (digitalRead(2) == HIGH);
}
void topInAtRandom()
{
int iterations = 0;
byte peek = array[0]; // stop when the botton card gets to the top
while (array[N - 1] != peek) {
iterations++;
byte card = array[N - 1]; // the top card
byte into = random(0, N); // in at random spot [0, N)
if (1) {
snprintf(buffer, 79, "top card %c goes in at %2d. -> ", 'A' + card, into);
Serial.print(buffer);
}
// move cards up, freeing the into slot
for (byte ii = N - 1; ii > into; ii--)
array[ii] = array[ii - 1];
// put that top card in the random slot
array[into] = card;
if (1) printArray();
}
snprintf(buffer, 79, "\niterations = %d\n", iterations);
Serial.print(buffer);
}
void printArray()
{
for (byte ii = 0; ii < N; ii++) {
snprintf(buffer, 79, "%c ", 'A' + array[ii]);
Serial.print(buffer);
}
Serial.println("");
}