Juho
Juho

Reputation: 1006

Partitioning a 2D array into "boxes" and indexing elements in the box

I have a grid or a 2D array of size N*N. Consider a 6*6 array like the following for example:

......
......
......
......
......
......

I am given two integers, height and width. The grid will be partitioned into boxes of this size, for example into 3*3 boxes like this:

... ...
... ...
... ...

... ...
... ...
... ...

The same 6*6 grid could be also divided into 2*3 boxes like this:

... ...
... ...

... ...
... ...

... ...
... ...

And so on. One can assume that the two integers given always divide the whole array evenly and neatly as above, if it matters. The problem is then that when I have a coordinate or a index into the array, I need to quickly index the neighbours of this particular coordinate. The neighbours are the points in the same box. For example, if the boxes were of size 2*3, the neighbours of (0,0) would be {(0,1),(0,2),(1,0),(1,1),(1,2)}. This doesn't seem too difficult, but I am unable to come up with anything even remotely simple. I am using C++, but this is language-independent.

Upvotes: 0

Views: 175

Answers (1)

Piotr Perak
Piotr Perak

Reputation: 11098

without trying to run this algorithm...

In pseudocode:

list_of_points find_neighbours_of(x, y, height_of_box, width_of_box)
{
    corner_x, corner_y = find_top_left_corner_of_box_containing(x, y)
    iterate over corner_x to corner_x + height_of_box
        iterate over corner_y to corner_y + width_of_box
            if current_x and current_y <> x, y add them to list
}

Upvotes: 1

Related Questions