# Thread: Two Dimensional Array Iteration Help

1. Member
Join Date
Mar 2011
Posts
26
Rep Power
0

## 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:
Java 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.

2. If you are looking for all the diagonals, manually find all of them and see if you see some pattern there.

3. Member
Join Date
Mar 2011
Posts
26
Rep Power
0
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...

4. 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?

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

Jos

5. Member
Join Date
Mar 2011
Posts
26
Rep Power
0
Trying to be a little clearer,

here is the equivalent of what I'm looking for in Python:
Java 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 ;)
Last edited by Stamoulohta; 03-13-2011 at 02:45 PM. Reason: typo

6. Member
Join Date
Mar 2011
Posts
26
Rep Power
0
Hey Jos,

this might be it!!!

Thank you!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•