Skip to content

Different Squares

Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.

Example

For

matrix = [[1, 2, 1],
          [2, 2, 2],
          [2, 2, 2],
          [1, 2, 3],
          [2, 2, 1]]

the output should be

different_squares(matrix) = 6

Here are all 6 different 2 × 2 squares:

- 1 2
  2 2

- 2 1
  2 2

- 2 2
  2 2

- 2 2
  1 2

- 2 2
  2 3

- 2 3
  2 1

Solution

py
def different_squares(matrix):
    squares = set()
    for i in range(len(matrix) - 1):
        for j in range(len(matrix[i]) - 1):
            squares.add(
                str([
                    [matrix[i][j], matrix[i][j+1]],
                    [matrix[i+1][j], matrix[i+1][j+1]],
                ]),
            )

    return len(squares)


print(different_squares(
    [
        [5, 2, 1],
        [2, 9, 2],
        [2, 2, 2],
        [1, 2, 3],
        [2, 2, 1]
    ]
))
js
function differentSquares(matrix) {
  const squares = new Set();
  for (let i = 0; i < matrix.length - 1; i++) {
    for (let j = 0; j < matrix[i].length - 1; j++) {
      squares.add(
        JSON.stringify([
          [matrix[i][j], matrix[i][j + 1]],
          [matrix[i + 1][j], matrix[i + 1][j + 1]],
        ])
      );
    }
  }

  return squares.size;
}

console.log(
  differentSquares([
    [5, 2, 1],
    [2, 9, 2],
    [2, 2, 2],
    [1, 2, 3],
    [2, 2, 1],
  ])
);

my thoughts are neither my employer's nor my wife's