jeudi 27 août 2015

Structure to run x first vs y first on 2d array

I want to have a flag passed to a function that runs an algorithm by either col-scanning or row-scanning:

if run-on-x
  for 1..x
    for 1..y
      do something with ary[x][y]

else
  for 1..y
    for 1..x
      do something with ary[x][y]

But I don't want to duplicate all the loops and logic.

I've come up with this:

let numPx = width * height;
for (let px = 0; px < numPx; px++) {
  let [x, y] = yAxis ? [px % width, 0 | px / width] : [0 | px / height, px % height];

But I think all the math is rather heavy, especially when I'm running it on fairly large arrays.

Is there a better way to do this?

Aucun commentaire:

Enregistrer un commentaire