// https://forum.arduino.cc/t/i-want-to-generate-the-random-number-but-not-duplicate/1031827
#include <KickSort.h>
/*
int myRand(int const low, int const high) {
static int last = random(low, high);
int value = random(low, high - 1);
if (value >= last) {
value++;
}
last = value;
return value;
}
*/
template <size_t n> int myRand(int const low, int const high) {
static int lasts[n]{}; // Initialisation is not perfect.
static size_t index = 0;
int sortedLasts[n];
memcpy(sortedLasts, lasts, n * sizeof(int));
KickSort<int>::quickSort(sortedLasts, n);
int value = random(low, high - n);
for (int const& last: sortedLasts) {
if (value >= last) {
value++;
}
}
lasts[index] = value;
index = (index + 1) % n;
return value;
}
void setup() {
Serial.begin(9600);
for (size_t i = 0; i < 20; i++) {
Serial.println(myRand<2>(0, 4));
}
}
void loop() {}