Created
May 16, 2023 05:11
-
-
Save evdokimovm/a06679332785a8029d8deb0f0ec67ffd to your computer and use it in GitHub Desktop.
check if the square matrix has enough space to fit the Tetris shape in using numpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def check_space(matrix): | |
shape = [ | |
[1, 1, 0], | |
[1, 0, 0], | |
[1, 0, 0] | |
] | |
shape_height = len(shape) | |
shape_width = len(shape[0]) | |
matrix_height = len(matrix) | |
matrix_width = len(matrix[0]) | |
for i in range(matrix_height - shape_height + 1): | |
for j in range(matrix_width - shape_width + 1): | |
can_fit = True | |
for si in range(shape_height): | |
for sj in range(shape_width): | |
if shape[si][sj] == 1 and matrix[i + si][j + sj] == 1: | |
can_fit = False | |
break | |
if not can_fit: | |
break | |
if can_fit: | |
return True | |
return False | |
matrix = [ | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 1, 1, 1, 1, 0], | |
[1, 0, 1, 0, 0, 1, 0, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0] | |
] | |
print(check_space(matrix)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def check_space(matrix): | |
shape = np.array([[1, 1, 0], | |
[1, 0, 0], | |
[1, 0, 0]] | |
) | |
for i in range(matrix.shape[0] - shape.shape[0] + 1): | |
for j in range(matrix.shape[1] - shape.shape[1] + 1): | |
sub_matrix = matrix[i : i + shape.shape[0], j : j + shape.shape[1]] | |
if np.all(sub_matrix + shape <= 1): | |
return True | |
return False | |
matrix = np.array( | |
[ | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 1, 1, 1, 1, 0], | |
[1, 0, 1, 0, 0, 1, 0, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0], | |
[1, 0, 1, 0, 1, 0, 1, 0] | |
] | |
) | |
print(check_space(matrix)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment