I added my Array to Paul Badgers code, using his random numbers without repeat to index my array:
/* RandomHat
Paul Badger 2007 - updated for Teensy compile 2017
choose one from a hat of n consecutive choices each time through loop
Choose each number exactly once before reseting and choosing again
*/
#define randomHatStartNum 0 // starting number in hat
#define randomHatEndNum 19 // ending number in hat - end has to be larger than start
#define numberInHat (randomHatEndNum - randomHatStartNum) + 1
const char *players[]={
"Student 1",
"Student 2",
"Student 3",
"Student 4",
"Student 5",
"Student 6",
"Student 7",
"Student 8",
"Student 9",
"Student 10",
"Student 11",
"Student 12",
"Student 13",
"Student 14",
"Student 15",
"Student 16",
"Student 17",
"Student 18",
"Student 19",
"Student 20",
};
void setup()
{
Serial.begin(9600);
Serial.println("start ");
}
void loop()
{ // randomHat test
for (int i = 1; i <= numberInHat; i++) {
int x = randomHat();
Serial.print(players[x]);
Serial.print(", ");
delay(50);
}
Serial.println(" ");
}
int randomHat() {
int thePick; //this is the return variable with the random number from the pool
int theIndex;
static int currentNumInHat = 0;
static int randArray[numberInHat];
if (currentNumInHat == 0) { // hat is emply - all have been choosen - fill up array again
for (int i = 0 ; i < numberInHat; i++) { // Put 1 TO numberInHat in array - starting at address 0.
if (randomHatStartNum < randomHatEndNum) {
randArray[i] = randomHatStartNum + i;
}
}
currentNumInHat = abs(randomHatEndNum - randomHatStartNum) + 1; // reset current Number in Hat
Serial.print(" hat is empty ");
delay(5000);
// if something should happen when the hat is empty do it here
}
theIndex = random(currentNumInHat); //choose a random index from number in hat
thePick = randArray[theIndex];
randArray[theIndex] = randArray[currentNumInHat - 1]; // copy the last element in the array into the the empty slot
// // as the the draw is random this works fine, and is faster
// // the previous version. - from a reader suggestion on this page
currentNumInHat--; // decrement number in hat
return thePick;
}
The output is as follows:
start
hat is empty Student 11, Student 24, Student 17, .......
hat is empty Student 4, Student 19, Student 23, .......
This gives me the result I need with two problems:
The first being the code first returns "hat is empty" before the numbers. Is there a way to reverse this?
And secondly, I would like define the randomHatEndNum automatic by the lenght of my custom array, but I have trouble implementing that code. What is the right way to approach this?