Two Dimensional Array Iteration Help

• 03-13-2011, 01:37 PM
Stamoulohta
Two Dimensional Array Iteration Help
Hi to all,

I'm trying to implement a maze creation class which needs a method to check the adjustment blocks (diagonal) to each block in my two dimensional array.

example:
Code:

```//field Block[][] maze = new Block[5][5]; //method pubic boolean chechAdj(int x, int y){ //[I]x[/I] and [I]y[/I] are the current Block's indexes.     int count = 0;     for(Block[] Xblocks : this.maze){ //how can I slice [I]this.maze[/I] to -1 and +1 of [I]x[/I] and [I]y[/I] [B]excluding[/B] [I]x[/I] and [I]y[/I]?         for(Block block : Xblocks){             if(block.wall == true) count +=1;         }     }     return count; }```
This example checks the whole array. As you can see from my comments, I would like an elegant and javaish way for checking only the adjustment Blocks of the current one.

Any help would be greatly appreciated.

Thank you in advance,
George.
• 03-13-2011, 01:50 PM
sunde887
If you are looking for all the diagonals, manually find all of them and see if you see some pattern there.
• 03-13-2011, 01:56 PM
Stamoulohta
Thanks for the reply.

I'm just interested in the adjustment diagonal Blocks and I know that the pattern is:
for x,y <-- block under check,

a) x-1,y-1
b) x+1,y-1
c) x-1,y+1
d) x+1,y+1

only those four blocks are of interest to me but I can't find an appropriate way to iterate them...
• 03-13-2011, 02:35 PM
JosAH
Quote:

Originally Posted by Stamoulohta
Thanks for the reply.

I'm just interested in the adjustment diagonal Blocks and I know that the pattern is:
for x,y <-- block under check,

a) x-1,y-1
b) x+1,y-1
c) x-1,y+1
d) x+1,y+1

only those four blocks are of interest to me but I can't find an appropriate way to iterate them...

How about two simple loops?

Code:

```for (dx= -1; dx <= 1; dx+= 2)   for (dy= -1; dx <= 1; dy+= 2)       // check position (x+dx, y+dy)```
kind regards,

Jos
• 03-13-2011, 02:36 PM
Stamoulohta
Trying to be a little clearer,

here is the equivalent of what I'm looking for in Python:
Code:

```>>> l = [[i for i in range(5)] for i in range(5)] >>> for i in l: ...    print i ... [0, 1, 2, 3, 4] [0, [B]1[/B], 2, [B]3[/B], 4] [0, 1, 2, 3, 4] [0, [B]1[/B], 2, [B]3[/B], 4] [0, 1, 2, 3, 4] >>> l[2][2]                          # this is the current block! 2 >>> def check(x,y): ...    for i in l[x-1:x+2:2]:        # This kind of [I]list slicing[/I] is ...        for j in i[y-1:y+2:2]:    # what I'm looking for in Java. ...            print j ... >>> check(2,2) 1 3 1 3 >>>```
Hope this helps Someone to help me ;)
• 03-13-2011, 02:39 PM
Stamoulohta
Hey Jos,

this might be it!!!

Thank you!