Answer the question
In order to leave comments, you need to log in
How to remove elements from an array in Arduino (c++)?
Welcome all!
The task, it seems to me, is simple to the point of impossibility, but I, apparently, have either been reworked or do not see the obvious things.
The essence is the following, there is an array of strings, by pressing the button you need to display a random string from this array.
There is only one condition: that the same line is not displayed twice.
I sketched a class, it stores the same array and has a function:
String StringClass::GetNextString() {
String result = "NONE";
if (LastStringCount == 0) {
return result;
}
randomSeed(analogRead(A1));
int index = random(0, LastStringCount );
result = StringList[index];
String tmp[LastStringCount -1];
int j = 0;
for(int i = 0; i < LastStringCount ; i++) {
if (i != index) {
tmp[j] = StringList[j];
Serial.println(tmp[j]);
j++;
}
}
LastStringCount--;
for(int i = 0; i < LastStringCount ; i++) {
StringList[j] = tmp[i];
}
}
return result;
}
Answer the question
In order to leave comments, you need to log in
I am changing the answer due to the fact that I found a solution.
The answer was prompted by the comment of comrade Roman
In general, the solution consists of two parts:
1. Leave the array of strings alone. Let it be in the form in which it was originally set.
2. Additionally, we create an array of numbers that will store the indices, and after selecting a random index, we do a "sorting" (it's more like a shift of one element, but still) already in the array of indices
int index = random(0, LastStringCount );
result = StringList[Indexes[index]];
int j = 0;
for(int i = 0; i < LastStringCount ; i++) {
if (i != index) {
Indexes[j] = Indexes[i];
Serial.println(Indexes[j]);
j++;
}
}
bool alreadyDisplayed [lastStringCount + 1];
for (int n = 0; n < lastStringCount; ++n)
alreadyDisplayed[n] = false;
int index;
do {
index = random(0, LastStringCount );
} while (alreadyDisplayed[index] == true);
alreadyDisplayed[index] = true;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question