Iterating through a list is trivial. In this case, a TCollection
property of a component I'm working on. I have no problem with iterating from 0
index to the maximum index - I've done it plenty of times.
However, I'm working on something now which needs to iterate a bit differently. I need to iterate through a list of collection items from any given starting point - and yet complete a full loop of all items. After the last list item, it shall automatically continue iteration from the beginning of the list.
To clarify: traditional iteration works like:
for X := 0 to SomeList.Count-1 do ...
But I may start it at some other point, such as:
for X := StartingPoint to EndingPoint do ...
And it's that "EndingPoint" which I cannot figure out. Iteration only increases. But in my case, I need to reset this current iteration position to the beginning - right in the middle of the iteration. EndingPoint
might be less than the StartingPoint
, but it still needs to do a complete loop, where once it reaches the end, it picks up from the beginning.
So, in a list of 5 items, rather than just going...
0, 1, 2, 3, 4
I may start at 2, and want to do...
2, 3, 4, 0, 1
How do I accomplish such a loop?
for foo := 0 to Pred(SomeList.Count) do begin
i := (foo + StartingPoint) mod SomeList.Count;
...
end;
Use the index i
inside the loop; ignore the foo
variable.
From the middle to the end of the range, i
will equal foo + StartingPoint
. After that, the mod
operator will effectively make i
"wrap around" to the start again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With