Defining a non-rectangular region in a grid by maximum and minimum x and y values

63 Views Asked by At

I'm working with a sort of grid, that can be defined as follows:

|0||1||2|
|3||4||5|
|6||7||8|

My goal is to define a region by its x and y values (or columns and rows). Let's say I have a region defined as R = [0, 1, 4], that means that the region is defined by the grid squares with the indices 0, 1 and 4. And so the expected output can be mathematically expressed by:

i ∈ R: { (col_i ∈ [0, 1] ∧ row_i = 0) ∨(col_i = 1 and row_i = 0)}

But I don't know how to achieve this, all I have, by now, is the availability to identify that the region isn't a rectangle with this:

region_indices=[0, 1, 4]
grid_size=3 #3 col x 3 row
rows=[]
cols=[]
for i in range(len(region_indices)):         
        row=i // grid_size
        col= i % grid_size
        rows.append(row)
        cols.append(col)

max_col=max(cols)
max_row=max(rows)
min_col=min(cols)
min_row=min(rows)

for row in range(min_row, max_row):
    for col in range(min_col, max_col):
           square_index=row*grid_size+col            
           if square_index in region_indices==False:
              isnt_rectangle=True

I was hoping someone could help me out with this, even if without the full answer to my question. And thanks in advance!

1

There are 1 best solutions below

0
Alain T. On

Your grid square numbers correspond to number = row*grid_size + col and can be converted into coordinates using row,col = divmod(number,grid_size).

To determine if the region is rectangular, you would need to find the minimum and maximum row and column indices of the region (i.e. top-left and bottom-right corners). Then check that you have exactly the number of items in the region to fill the area of the corresponding rectangle:

def isRectangle(region,size=3):               # size is the number of columns
    coord = [divmod(n,size) for n in region]  # convert to coordinates
    rows,cols = zip(*coord)                   # isolate rows and columns
    minRow,maxRow = min(rows),max(rows)
    minCol,maxCol = min(cols),max(cols)
    return len(region) == (maxRow-minRow+1) * (maxCol-minCol+1)


print(isRectangle([0,1,4]))   # False
print(isRectangle([0,1,4,3])) # True 

Depending on what you intend to do with the region, it may be useful to transform it into a set of coordinates:

coordSet = {divmod(n, grid_size) for n in region_indices}

which would allow you to test coordinates against the region:

if (2,3) in coordSet:
   ...

Expressing the region mathematically, as you did in the example, isn't generally useful in a program. Your data structures and representation models will need to align with the kind of processing you're doing on the data.