Demo file: traverse-arrays-with-mod-and-floor.zip
Introduction
Today I want to talk about a technique that can come in handy if you need to walk a block of contiguous cells within a 2-dimensional JSON array for either reading and/or writing purposes.
[ [ n, n, n, n, n, n, n, n, n, n, n, n, n, n, n ], [ n, n, n, n, n, n, n, n, n, n, n, n, n, n, n ], [ n, n, n, n, n, n, n, n, n, n, n, n, n, n, n ], [ n, n, n, n, n, n, n, n, n, n, n, n, n, n, n ] ]
The standard approach would be to employ a While within a While, the outer to walk the columns and the inner to walk the rows (or vice-versa). And that’s a very valid way to go about it, but I was wondering whether a 2-dimensional array of arbitrary height and width could be traversed via a single While call. Well it turns out that yes, it is possible, and we’re going to look at an approach that can accomplish this with help from the Mod() and Floor() functions.
Let’s say we have a 4 row × 15 column array, for a total of 60 cells that we want to iterate through. Since JSON uses zero based indexing, we can consider the rows to be numbered 0 – 3 and the columns to be numbered 0 – 14 like so.

Assume that our task is to fill the array with the letters A through Z, one letter per cell, starting with column [0] and populating all the rows in each column before moving on to the next column. Since there are only 26 letters in the English alphabet, after Z has been assigned start with A again, and keep iterating through the sequence until all 60 cells have been populated (and while we’re at it, let’s go with lower-case letters to make it easier on the eyes).
Conceptually, it looks like this…

…and as JSON, like this.





