// DoTheShuffle.ino
//
// By : Koepel, 14 December 2021
// Fisher-Yates shuffle
// From example by Arduino user J-M-L
// https://forum.arduino.cc/t/random-0-and-1-integers/935832/12
// Adapted for Raspberry Pi Pico in Wokwi simulation
// Raspberry Pi Pico has 264kbyte internal ram.
//
#define SIZE 60000UL // use an even number
byte myArray[SIZE];
const size_t arraySize = sizeof myArray / sizeof myArray[0];
unsigned long numShuffles = 0; // the numbers of shuffles
// Fisher–Yates shuffle
void shuffle()
{
for (size_t i = arraySize - 1; i > 0; --i)
{
size_t r = random(0, i + 1);
byte tmpSwap = myArray[i];
myArray[i] = myArray[r];
myArray[r] = tmpSwap;
}
numShuffles += 1;
}
// Exchange two random locations, 100 times.
void xchgShuffle()
{
for( int i=0; i<100; i++)
{
size_t randIndex1 = random( 0, SIZE);
size_t randIndex2 = random( 0, SIZE);
byte temp = myArray[randIndex1]; //temporary integer for
myArray[randIndex1] = myArray[randIndex2]; //swapping the values
myArray[randIndex2] = temp; //swapping the values
}
numShuffles += 100;
}
void show()
{
for (auto &n : myArray)
Serial1.print(n);
Serial1.println();
}
void tell()
{
// Count zeros in first half
size_t count = 0;
for( size_t i=0; i<SIZE/2; i++)
if( myArray[i] == 0)
count++;
Serial1.print( "Number of shuffles = ");
Serial1.print( numShuffles);
Serial1.print( ", Percentage zeros in first half is: ");
float percentage = float(count) / float(SIZE/2) * 100.0;
Serial1.println( percentage);
}
void setup()
{
Serial1.begin(115200);
Serial1.println("The sketch has started");
randomSeed(analogRead(A0)); // randomize
// First half with zeros
for( size_t i=0; i<SIZE/2; i++)
myArray[i] = 0;
// Second half with ones
for( size_t i=SIZE/2; i<SIZE; i++)
myArray[i] = 1;
Serial1.println( "First one is before shuffling");
tell();
}
void loop()
{
// Select one of the two shuffle methods
shuffle();
//xchgShuffle();
tell();
delay( 500);
}