I have Googled for a simple method to sum elements in a segment of a circular array. So far nothing that is better than my first attempt.
Perhaps it is best to use a real world example, one that started my quest. I have built an irrigation controller, and I record rain in mm for each hour (0-23). That was easy, I used a MRMP array.
*(rainDuringHour210 + hourToday( *TZ300 - 1)) = mmB; // A byte array of 24 elements 0 to 23 matching the previous hour.
In this graphic, 2 mm recorded in element 0, and 8 mm in element 6, totaling 10mm.
My irrigate controller must know the total rain during the previous x hours.
Now the tricky part...
The code I created to perform this task is flexible, in that it allows me to reuse the index calculation for other circular arrays. It handles indexes that are multiple times the size of the circular array.
In this case, I have an array, *rainDuringHour210, starting at 0, and ending at 23.
I want the indexes for each element from 05:00, back 9 hours to 21:00. Notice that crosses 0, which is not too difficult to handle.
// Constrain Index
// Returns an absoulte index to a rolling range from start + index.
int ConstrainFromIndexInt(int minimum, int maximum, int start, int index)
{
maximum++;
start = constrain(start,minimum,maximum); // be sure start is within the range
if(minimum < 0)
{
maximum--;
minimum--;
}
index = (index + start) % (maximum - minimum); // Go round and round and land within minimum and maximum
if(index > maximum)
{
index = minimum + (index - maximum);
}
if(index < minimum)
{
index = maximum + index;
}
return index;
}
So how do I use it?
// Return total rain in mm x10 in the previous x hours
int rainPreviousHours(int hours)
{
hours = constrain(hours,1,24);
int mm = 0;
for(hours; hours >= 1 ; hours--)
{
// segments array rainDuringHour210 and wraps around at 23 -> 0
mm = mm + *(rainDuringHour210 + ConstrainFromIndexInt(0, 23, hourToday(*TZ300), -hours));
}
return mm * 10; // 200 series array did not save decimal.
}
Any suggestions about simplifying ConstrainFromIndexInt(
- George
What are MRMP arrays?
http://www.mmcs.com/~gmatthews/FAV1-00012D85/S0005027B-0005027B