More than once I've needed to start at some point in an array and work my way out to the edges. I don't want to have to figure this out again next time so here's the code.

The assumption is that I have an array (of integers) and instead of accessing them in order (0..n) I want to access them as (k,k+1,k-1,k+2,k-2,…,n,0) where at the end there may be several positive (i > k) or several negative (i < k) index in a row because the start point (k) might not be dead center of an odd length array.

This code is based on MFC CArrays, your mileage may vary slightly.

```
IntArray *pSel = GetArray(); // a populated array
int start_point = pSel->GetSize() / 2; // start in the middle for this example
IntArray spiral; // our new order
// add the starting point outside the loop so it doesn't get added twice. +/- 0
spiral.Add( start_point );
for ( int diff = 1, n = pSel->GetSize(); ; )
{
int i = start_point + diff;
if ( i >= 0 && i < n )
spiral.Add( i ); // the index into our array
if ( diff < 0 ) diff--;
diff *= -1;
if ( -i < 0 && i > n ) break; // we've exceeded both ends of the array
}
ASSERT( spiral.GetSize() == pSel->GetSize() );
for ( int i = 0, n = spiral.GetSize(); i < n ; i++ )
{
int j = spiral[i];
int value = pSel->GetAt( j );
DoSomething( value );
}
```

Comments: 0