Skip to content

Instantly share code, notes, and snippets.

@ancms2600
Created February 19, 2020 21:06
Show Gist options
  • Save ancms2600/b1c8a924287498aaa18474861ac18033 to your computer and use it in GitHub Desktop.
Save ancms2600/b1c8a924287498aaa18474861ac18033 to your computer and use it in GitHub Desktop.
Efficient Cell Array data structure walker. (No functions. No recursion.)
// The following is useful when building a
// streaming cartesian product (ie. cross join)
// e.g., Imagine walking a two-dimensional matrix
// having one [column] dimension given and fixed at initialization,
// and one dimension of varying, perhaps infinite, lengths [determined by each row].
// A set of nested for...loop would normally accomplish this,
// if it weren't for the number of loop statements required varying by invocation.
const size = 3; // matrix size variable
const len = [3,2,3]; // the length of each list in the matrix (notice they can vary)
const cur = [0,0,0]; // the current position / cursor in each list
let p = 0; // a stack pointer used when incrementing the cursor position through each list
// visit every position in the matrix, the same way a set of nested for...loops would
while (p === 0) {
// do stuff
console.log(`pos=${cur.join(',')}`);
// step
cur[0]++;
while (cur[p] === len[p]) {
cur[p] = 0;
++p;
// if we have incremented the root-most loop beyond its length
if (p >= size) {
// could also return; we're done
break;
}
cur[p] += 1;
if (cur[p] !== len[p]) {
p = 0;
break;
}
}
}
console.log('done');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment