0

I have a 36x25 grid of nodes that I wish to search through all triangular numbers from the corner opposite of the hypotenuse. Here's psuedocode for what I was considering, but this method only works until it hits the next corner of the grid, and I'm sure there is a much simpler way to do this recursively, I just am having difficulty figuring it out.

for(int iteration; iteration < maxDistance(49); iteration++)
{
    int xAdd = iteration;
    int yAdd = 0;
    while(xAdd != 0)
    {
        checkStuff(nodeGrid[x+xAdd][y+yAdd]);
        xAdd--;
        yAdd++;
    }
}

What I want program to do:

[0][1][2][3][4][5]
[1][2][3][4][5][6]
[2][3][4][5][6][7]
[3][4][5][6][7][8]
[4][5][6][7][8][9]

check in this order. So first check all tiles with value 0, then 1 and so on.

Note: in this case my function will only work up until the 4th set up tiles. Any further and it will reach out of bounds.

SpiderShlong
  • 224
  • 1
  • 8
  • Those aren't triangular numbers, triangular number start with : `1,3,6,10,...` They are the numbers that are of the form `n*(n+1)/2`. Also, are you sure you want to do it recursively? – Justin Nov 07 '13 at 06:34
  • it would represent the form of a triangular number set if the source was one of the other corners instead. Not sure what term is for my number form. And since my grid isn't a perfect square I figured recursion would be the simplest solution to the problem. If you are aware of a better way to do so within a loop without adding too many conditionals I'd love to hear your solution as well. – SpiderShlong Nov 07 '13 at 06:39

1 Answers1

0
/**
 * Only works for rectangular arrays
 */
public void iterateOver(Node[][] a){
    int x_dim = a[0].length;
    int y_dim = a.length;

    for (int i = 0; i < x_dim + y_dim - 1; i++){
        int x, y;
        if (i < x_dim){
            x = i;
            y = 0;
        }
        else{
            x = x_dim - 1;
            y = i - x_dim + 1;
        }
        for (;x >=0 && y < y_dim; y++, x--){
            doStuff(a[y][x]);
        }

    }
}

How it works

Picture your rectangular array:

[0][1][2][3][4][5]
[1][2][3][4][5][6]
[2][3][4][5][6][7]
[3][4][5][6][7][8]
[4][5][6][7][8][9]

There are clearly 6 columns and 5 rows (or 6 x values and 5 y values). That means that we need to do 6 + 5 - 1 iterations, or 10. Thus, the for (int i = 0; i < x_dim + y_dim - 1; i++). (i is the current iteration, measured from 0). We start by columns. When i is less than the x dimension, x = i and y = 0 to start with. x is decremented and y is incremented until x is less than zero or y is equal to the y dimension. Then, we do a similar thing down the right hand side.

Justin
  • 24,288
  • 12
  • 92
  • 142