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

List iterating is trivial. In this case, the TCollection property of the component I'm working on. I have no problem iterating from index 0 to maximum index - I have done this many times.

However, I am currently working on something that needs to be sorted out differently. I need to iterate over the list of collection elements from any given starting point - and still complete the full cycle of all elements. After the last element of the list, it will automatically continue iterating from the beginning of the list.

To clarify: traditional iteration works as follows:

 for X := 0 to SomeList.Count-1 do ... 

But I can start it in another place, for example:

 for X := StartingPoint to EndingPoint do ... 

And this is what is "EndingPoint" which I cannot understand. The iteration is only increasing. But in my case, I need to reset the current iteration position at the beginning - right in the middle of the iteration. EndingPoint may be smaller than StartingPoint , but it should still do a full cycle where, when it reaches the end, it rises from the very beginning.

So, in a list of 5 items, not just ...

 0, 1, 2, 3, 4 

I can start with 2, and want to do ...

 2, 3, 4, 0, 1 

How to carry out such a cycle?

+7
list loops delphi
source share
1 answer
 for foo := 0 to Pred(SomeList.Count) do begin i := (foo + StartingPoint) mod SomeList.Count; ... end; 

Use index i inside the loop; ignore foo variable.

From the middle to the end of the range i will be equal to foo + StartingPoint . After that, the mod statement will actually make i "wrapped" to the beginning again.

+15
source share

All Articles