Omid - Challenge 370

data-challenges
advanced-exercises
🔰 In Table 1, extract all sub-matrices with the sum equal to 16.
Published

March 24, 2026

Illustration for Omid - Challenge 370

Challenge Description

🔰 In Table 1, extract all sub-matrices with the sum equal to 16.

Solutions

library(tidyverse)
library(readxl)

path <- "300-399/370/CH-370 Matrix Calculation.xlsx"
mat <- read_excel(path, range = "C4:G7", col_names = FALSE) %>%
  as.matrix()

find_submatrices <- function(mat, target) {
  n_rows <- nrow(mat)
  n_cols <- ncol(mat)
  submatrices <- list()

  for (start_row in 1:n_rows) {
    for (start_col in 1:n_cols) {
      for (end_row in start_row:n_rows) {
        for (end_col in start_col:n_cols) {
          submatrix <- mat[start_row:end_row, start_col:end_col]
          if (sum(submatrix) == target) {
            submatrices <- append(submatrices, list(submatrix))
          }
        }
      }
    }
  }

  return(submatrices)
}
target_sum <- 16
result <- find_submatrices(mat, target_sum)
print(result)
  • Logic:

    • Reads the workbook ranges needed for the challenge

    • Applies the rule iteratively until the output stabilizes

  • Strengths:

    • The R solution stays close to the workbook rule and keeps the transformation compact.
  • Areas for Improvement:

    • The code assumes the sheet structure and source ranges remain stable.
  • Gem:

    • The strongest part of the solution is choosing the right intermediate representation before shaping the final output.
import pandas as pd
import numpy as np

path = "300-399/370/CH-370 Matrix Calculation.xlsx"
mat = pd.read_excel(path, sheet_name=0, usecols="C:G", skiprows=3, nrows=4, header=None).to_numpy()

def find_submatrices(mat, target):
    mat = np.array(mat)
    n_rows, n_cols = mat.shape
    submatrices = []

    for start_row in range(n_rows):
        for start_col in range(n_cols):
            for end_row in range(start_row, n_rows):
                for end_col in range(start_col, n_cols):
                    submatrix = mat[start_row:end_row+1, start_col:end_col+1]
                    if submatrix.sum() == target:
                        submatrices.append(submatrix)

    return submatrices

target_sum = 16
result = find_submatrices(mat, target_sum)
print(result)
  • Logic:

    • Reads the workbook ranges needed for the challenge

    • Applies the rule iteratively until the output stabilizes

  • Strengths:

    • The Python version follows the same rule in a direct dataframe-oriented implementation.
  • Areas for Improvement:

    • The code assumes the workbook layout remains stable, so any sheet redesign would require small adjustments.
  • Gem:

    • The implementation stays close to the original workbook rule instead of adding unnecessary abstraction.

Difficulty Level

This task is moderate:

  • The business rule is readable, but the workbook still requires careful implementation to reach the expected layout.