'Iteration pattern forth and back

I'm trying to go through a list where n is the length of the list the pattern would be the first element, n, second element, n-1, the third element, n-2...

how is this possible?



Solution 1:[1]

You'd generally use two indices and repeat what needs to be done twice:

for (int lo = 0, hi = n - 1; hi <= lo; ++lo, --hi) {
  doStuff(list.get(lo));
  if (lo == hi) break;  // don't handle a middle element twice.
  doStuff(list.get(hi));
}

If you really need a bouncing single index, that's possible but ugly:

for (int d = 0; d < n; ++d) {
  int i = (d & 1) == 0 ? (d / 2) : (n - 1 - (d / 2));
  doStuff(list.get(i));
}

If this is a common operation, you'd want to define an Iterator that hides the ugliness.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gene