Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
Nobody Avatar asked Aug 27 '15 12:08

Nobody


2 Answers

Perhaps by simply passing them in as parameters like so?:

  function colRowScan(1stAxis,2ndAxis)
      for 1.. 1stAxis
        for 1.. 2ndAxis
          do something with ary[x][y]

Without seeing what the "do something" is I don't know if there is any unforeseen reasons why this couldn't work but given what you posted it should do the trick.

I am not entirely sure what you are trying to do here:

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];
like image 163
IfTrue Avatar answered Oct 23 '22 04:10

IfTrue


function f(x, y, on_x) {
    var a, b;

    if (on_x) {
        a = x;
        b = y;
    } 
    else {
        a = y;
        b = x;
    }

    for (var ia = 0; ia < a.length; ia++) {
        for (var ib = 0; ib = b.length; ib++) {
            // ...
        }
    }
}
like image 41
Vidul Avatar answered Oct 23 '22 03:10

Vidul