Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through list from any given starting point and continue from beginning?

Tags:

loops

list

delphi

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?

like image 688
Jerry Dodge Avatar asked Aug 07 '16 02:08

Jerry Dodge


1 Answers

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.

like image 81
Rob Kennedy Avatar answered Nov 13 '22 07:11

Rob Kennedy