Created
August 27, 2024 23:24
-
-
Save maulikmadhavi/6afcca4ae44c736db0c5012e375704de to your computer and use it in GitHub Desktop.
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
| # I have the matrix in the form of 1s and 0s. The size of matrix is 3x4. | |
| # I want to find if any two adjacent row or columns elments are equal to 1, then code should return 1, else 0. | |
| # For example: | |
| # x1 = [[1, 0, 0, 0],[1, 0, 0, 0],[0, 0, 0, 0]] => 1 | |
| # x2 = [[1, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]] => 0 | |
| # x3 = [[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 0]] => 0 | |
| # x4 = [[1, 0, 0, 0],[0, 0, 0, 0],[0, 0, 0, 1]] => 0 | |
| # x5 = [[1, 0, 0, 0],[0, 0, 0, 0],[0, 0, 1, 0]] => 0 | |
| # x6 = [[1, 1, 0, 0],[0, 0, 0, 0],[0, 0, 0, 0]] => 1 | |
| def check_adjacent_ones(matrix): | |
| # Check rows | |
| for row in matrix: | |
| for i in range(len(row) - 1): | |
| if row[i] == 1 and row[i+1] == 1: | |
| return 1 | |
| # Check columns | |
| for col in range(4): | |
| for row in range(2): | |
| if matrix[row][col] == 1 and matrix[row+1][col] == 1: | |
| return 1 | |
| return 0 | |
| # Test cases | |
| x1 = [[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]] | |
| x2 = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] | |
| x3 = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]] | |
| x4 = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]] | |
| x5 = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0]] | |
| x6 = [[1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] | |
| print(check_adjacent_ones(x1)) # Expected output: 1 | |
| print(check_adjacent_ones(x2)) # Expected output: 0 | |
| print(check_adjacent_ones(x3)) # Expected output: 0 | |
| print(check_adjacent_ones(x4)) # Expected output: 0 | |
| print(check_adjacent_ones(x5)) # Expected output: 0 | |
| print(check_adjacent_ones(x6)) # Expected output: 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment