Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a grid

Tags:

java

loops

I use these two simple loops to search through a grid from height to bottom, right to left.

for(int y=0; y<height; y++){
  for(int x=width; x>=0; x--){
  }
}

Basically, I want to search through the grid sideways like the numbers in the picture below until it covers all the cells. My approach hasn't worked out well so I'm asking for help here.

enter image description here

How can I accomplish this the quickest way possible? I believe this should be possible to do using just two loops but I can't figure it out.

like image 786
Paul Smock Avatar asked May 01 '12 07:05

Paul Smock


1 Answers

The following will do it:

 final int h = 4;
 final int w = 3;
 for (int d = 0; d < w + h; d++) {
     for (int y = 0; y < h; y++) {
         int x = w - d + y;
         if (x < 0 || x >= w) continue;
         System.out.printf("%d %d\n", x, y);
     }
 }

Here, h is the height and w is the width of the grid.

The algorithm is based on the observation that for each diagonal, the sum of the distances to the top edge and to the right edge remains constant.

The outer loop iterates over the diagonals; the inner loop, over all cells on the diagonal.

like image 180
NPE Avatar answered Nov 13 '22 04:11

NPE