N
N
Nikolay Alekseev2020-02-02 00:32:01
Arduino
Nikolay Alekseev, 2020-02-02 00:32:01

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;
}

So, at the stage of filling the temporary array, empty lines are periodically output to the port, periodically cut off, and byte by byte, that is, some characters are cut off in the middle.

I am asking for advice from more experienced comrades. I tried to work with dynamic memory allocation through new and delete, but due to the fact that all this works on pointers, I could not return the string value of the function.

The lack of experience is catastrophic.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolai Alekseev, 2020-02-02
@VariusRain

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++;
        }
    }

V
vanyamba-electronics, 2020-02-02
@vanyamba-electronics

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 question

Ask a Question

731 491 924 answers to any question