Home > Net >  Is there a way to detect squares drawn by characters in a two-dimensional array?
Is there a way to detect squares drawn by characters in a two-dimensional array?

Time:01-13

I have a project in Python where you have a 5x4 two-dimensional list with empty strings as elements. These "slots" are later filled in with either "A" or "B", depending on the user input. After all the elements are changed with A's or B's, I want to find out how many 2x2 squares that are made up only by A's and B's (if they form at all) after there are 20 inputs. [If a formation like this occurs, it should count as two squares.]

2

I can't wrap my head around this. So any help would be appreciated.

(I can't use any kind of third party libraries. But any built-in Python library would be OK.)

CodePudding user response:

A 2x2 square contains just a single value. Thus, if you form the set of those 4 elements, that set would have length 1. This is easy enough to implement:

def count_squares(mat):
    m = len(mat) #number of rows
    n = len(mat[0]) #number of columns
    count = 0
    for i in range(m-1):
        for j in range(n-1):
            if len(set([mat[i][j],mat[i][j 1],mat[i 1][j],mat[i 1][j 1]])) == 1:
                count  = 1
    return count

mat = [['A','A','A','B','B'],
       ['A','A','B','A','A'],
       ['A','A','B','B','A'],
       ['B','A','A','B','A']]

print(count_squares(mat)) #prints 2

CodePudding user response:

Here is your code:

import numpy

def main(l1, l2, A, B, input_list):
    check = numpy.ones((l1, l2)) * A
    pos = []
    for j1 in range(len(input_list) - l1   1):
        for j2 in range(len(input_list[0]) - l2   1):
            if input_list[j1:j1 l1, j2:j2 l2].all() == check.all():
                pos.append([j1, j2])
    return pos

if __name__ == "__main__":
    A = 1  # Value of A
    B = 0  # Value of B
    l1 = 2  # Horizontal size of A values searched
    l2 = 2  # Vertical size of A values searched
    input_list = numpy.array([  # User input
        [A, A, A, B, B],
        [A, A, B, A, B],
        [A, A, B, B, A],
        [B, A, A, B, A],
    ])
    
    pos = main(l1, l2, A, B, input_list)
    
    print(f"{input_list = }")
    print(f"{pos = }")

Result:

input_list = array([[1, 1, 1, 0, 0],
       [1, 1, 0, 1, 0],
       [1, 1, 0, 0, 1],
       [0, 1, 1, 0, 1]])
pos = [[0, 0], [1, 0]]

The output return the top left corner of square of 2x2 containing only 1 values. Here you just need the len of 'pos' to count how many square you have...

  •  Tags:  
  • Related