I was wondering if anyone can give me some tips on using nested for loops to check characters diagonally in like an 8x8 2D array.
I know how to check rows and columns by reversing the variables in the for statement
for(i = 0; i < whatever; i++)
for(j = 0; j < whatever; j++)
{
whatever code inside
}
Then just reversing the for loops with j 1st then i. But I am having some difficulty on checking the 2D array diagonally(in both directions). If anyone knows how to do it, I would really appreciate the knowledge. THANK YOU!!!!!
biosx
09-08-2002, 10:23 AM
Well your question is kind of hard to decipher, but I'll give it a shot. So first lets make a 2D array to work with (I'm going to make mine a little smaller):
int array2D[5][5] = {
{0, 1, 2, 3, 4},
{1, 2, 3, 4, 5},
{2, 3, 4, 5, 6},
{3, 4, 5, 6, 7},
{4, 5, 6, 7, 8}
};
To figure this out, you will need to look at the coordinates of each of the elements you want. Since we are going diagnal, you will want to check these indexes:
[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]
It is pretty easy to see the pattern, and you don't need a nested loop:
for(i = 0, j = 0; i < 5; i++, j++)
printf("[%d][%d] = %d\n", i, j, array2d[i][j]);
Using the same technique to go backwards should be pretty easy to figure out.
I hope this helps. I'm not sure exactly what you wanted.
I am using C++.
I need to check the coordinates diagonally of an 8x8 array. So I need to check all 15 diagonal lines in this direction --> / and in this direction --> \.
so in this direction --> / it would be the cooordinates
00
01 10
02 11 20
03 12 21 30
04 13 22 31 40
05 14 23 32 41 50
06 15 24 33 42 51 60
07 16 25 34 43 52 61 70
This would be for the upper left half of the grid. Then would have to go and do the lower right half to complete the diagonals in this
/ direction. Could the array be checked in this direction / without having to do start over again for the lower right half of the grid?
And then when this / direction is finished being checked, I would need to check in this \ direction. If I could get some idea on how to do this, I would be able to figure out the other direction.
biosx
09-08-2002, 09:30 PM
Maybe if you could explain the bigger picture of this program, I could help you a little bit more.
Like I said, just use the technique that I used before. Look at the indexes that are within the diagonal. A pattern should be shared between the indexes. Use that pattern to create a loop to go through it.