Array FIFO - First In First Out without manually shifting array contents
in
Programming Questions
•
2 years ago
Hi everyone. I've searched the forums and haven't been able to find anything related to what I'm trying to do. I've been able to do it manually but I'm hoping for a more elegant solution.
I have a String array that's 10 elements long that I want to store incoming serial data in. But I want the newest data to be element [0], and the second newest to be [1] and so on - until the oldest incoming data gets "pushed off" the end of the array and deleted. So everything gets pushed down one element whenever new data comes in. I believe this is called FIFO (First In First Out).
I can easily accomplish this like so: (shortened to 3 elements)
lastThreeStrings[2] = lastThreeStrings[1];
lastThreeStrings[1] = lastThreeStrings[0];
lastThreeStrings[0] = incomingSerialString;
A while back I tried putting this into a loop and it didn't work, so I reverted to the above method but with 10 strings.
So the question is this: is there a more elegant way to do what I'm trying to do?
I thought of something like this:
lastThreeStrings = reverse(lastThreeStrings);
lastThreeStrings = shorten(lastThreeStrings);
lastThreeStrings = reverse(lastThreeStrings);
lastThreeStrings = expand(lastThreeStrings, 1);
But that seems a bit convoluted too, although it might seem less convoluted if I had an array with thousands of elements.
Any ideas? Thanks in advance.
I have a String array that's 10 elements long that I want to store incoming serial data in. But I want the newest data to be element [0], and the second newest to be [1] and so on - until the oldest incoming data gets "pushed off" the end of the array and deleted. So everything gets pushed down one element whenever new data comes in. I believe this is called FIFO (First In First Out).
I can easily accomplish this like so: (shortened to 3 elements)
lastThreeStrings[2] = lastThreeStrings[1];
lastThreeStrings[1] = lastThreeStrings[0];
lastThreeStrings[0] = incomingSerialString;
A while back I tried putting this into a loop and it didn't work, so I reverted to the above method but with 10 strings.
So the question is this: is there a more elegant way to do what I'm trying to do?
I thought of something like this:
lastThreeStrings = reverse(lastThreeStrings);
lastThreeStrings = shorten(lastThreeStrings);
lastThreeStrings = reverse(lastThreeStrings);
lastThreeStrings = expand(lastThreeStrings, 1);
But that seems a bit convoluted too, although it might seem less convoluted if I had an array with thousands of elements.
Any ideas? Thanks in advance.
1