I would like to iterate over an array but I want to pick whether the iteration is column wise or row wise. In other words, I want to define each time at runtime, whether rows
or cols
goes to the outer loop, against a condition. The dummy implementation of course would be:
if cond:
for rows:
for cols:
ar[rows][cols];
elif !cond:
for cols:
for rows:
ar[rows][cols];
Now, is there a compressed way to express the above implementation?
Unfortunately, going over all cases (my array is 4-dimensional, so I have 16 cases) is not the best way to go.
So, is there any algorithmic approach that compresses these loops into one loop?
Statically-allocated arrays of the same type can be treated as being 1-dimensional if you're careful - in this case, you can calculate the Nth-offset within it (perhaps with a new function) and iterate over those indices rather than by the I,J,K,L-th member.
Alternatively, if you have a language which doesn't allocate static arrays or you can't use one for some reason (fully dynamic type system?), you may instead be able to put the starting pointers into a new array and iterate over that array (which is cheap as it'll only have 4 members in your case), using each as the starting point!
You may find you need to create a logical view into the first array from the second with a different ordering.
In both cases, you likely want to wrap with a modulo %
operator, which will allow you to keep adding your sub-indices together while calculating offsets that wrap around the length of your array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.