Rhombus area calculation

whitehousechef·2024년 9월 5일

question

imagine we are trying to calculate the area of a rhombus in a 2x2 matrix with a certain radius.

solution

This radius takes (radius-1) elements to its left and right from the center position. So I need to centerX-(radius-1) and centerX+(radius-1) when checking the boundaries.

def solution(matrix, radius):
    rows = len(matrix)
    cols = len(matrix[0])
    max_sum = float('-inf')  # Initialize max_sum to the smallest possible value

    # Helper function to calculate the sum of a rhombic area
    def calculate_rhombic_sum(centerX, centerY, radius):
        total = 0
        for x in range(rows):
            for y in range(cols):
                distance = abs(centerX - x) + abs(centerY - y)
                if distance <= radius-1:
                    total += matrix[x][y]
        return total

    # Iterate over all possible center cells
    for centerX in range(rows):
        for centerY in range(cols):
            if centerX - radius +1 >= 0 and centerX + radius -1 < rows and centerY - radius +1 >= 0 and centerY + radius -1 < cols:
                current_sum = calculate_rhombic_sum(centerX, centerY, radius)
                max_sum = max(max_sum, current_sum)
    print(max_sum)
    return max_sum

solution([[0, 2, 4, 1, 6, 4],
          [5, 1, 3, 4, 1, 5],
          [0, 1, 2, 1, 2, 1],
          [1, 3, 2, 1, 1, 2],
          [4, 1, 3, 6, 5, 5],
          [6, 7, 5, 3, 1, 2]], 3)

0개의 댓글