You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

需求:编写生成指定行列和的0-8非负整数矩阵的函数

解决思路与实现代码

Got it, let's tackle this problem step by step. First, we need to clarify the constraints and prerequisites for a valid solution—otherwise, we might end up writing a function that can't generate a legal matrix at all.

有解的必要前提

To generate a matrix that meets your requirements, these conditions must all be satisfied:

  • The length of sumForEveryRow (number of rows) must equal the length of sumForEveryCol (number of columns), and this length must be at least 5. Since each element can be at most 8, you need at least 5 elements per row to reach a sum of 40 (5×8=40), and the same logic applies to columns.
  • Every value in sumForEveryRow must be 40, and every value in sumForEveryCol must also be 40 (this is what you specified, but we'll add checks to avoid invalid inputs).

If these prerequisites aren't met, the problem has no solution, and the function will throw a clear error.

核心思路:带约束的贪心填充

We'll use a greedy algorithm to fill the matrix cell by cell. The key is to not only consider the remaining sum for the current row and column but also ensure the remaining cells can still reach their target sums—so we don't overfill early and get stuck later. Here's the step-by-step logic:

  1. Make copies of the row and column sums to track remaining targets (we don't want to modify the original inputs).
  2. Initialize an empty n×n matrix filled with zeros.
  3. Iterate over each cell (i,j):
    • Calculate the minimum valid value for the cell: this ensures that even if all remaining cells in the row/column are filled with 8, we can still reach the target sum. The formula is: max(0, remaining_row[i] - 8*(n-j-1), remaining_col[j] - 8*(n-i-1))
    • Calculate the maximum valid value: can't exceed 8, the remaining sum for the current row, or the remaining sum for the current column. Formula: min(8, remaining_row[i], remaining_col[j])
    • Pick a value in this range (we'll use the maximum for efficiency), fill the cell, then update the remaining row and column sums.
  4. Once all cells are filled, the matrix will meet all your requirements.

Python代码实现

def generate_valid_matrix(sumForEveryRow, sumForEveryCol):
    # Step 1: Validate input prerequisites
    n_rows = len(sumForEveryRow)
    n_cols = len(sumForEveryCol)
    
    # Check if rows and columns count match and are at least 5
    if n_rows != n_cols or n_rows < 5:
        raise ValueError("The number of rows and columns must be equal and at least 5")
    
    # Check if all row and column sums are exactly 40
    if any(row != 40 for row in sumForEveryRow) or any(col != 40 for col in sumForEveryCol):
        raise ValueError("All row sums and column sums must be 40")
    
    # Initialize remaining sums for rows and columns
    remaining_row = sumForEveryRow.copy()
    remaining_col = sumForEveryCol.copy()
    
    # Create an empty zero matrix
    matrix = [[0 for _ in range(n_cols)] for _ in range(n_rows)]
    
    # Fill the matrix cell by cell
    for i in range(n_rows):
        for j in range(n_cols):
            # Calculate minimum value to ensure remaining cells can reach target sums
            min_val = max(
                0,
                remaining_row[i] - 8 * (n_cols - j - 1),  # Remaining columns filled with 8 can hit row target
                remaining_col[j] - 8 * (n_rows - i - 1)   # Remaining rows filled with 8 can hit column target
            )
            # Calculate maximum allowed value
            max_val = min(8, remaining_row[i], remaining_col[j])
            
            # Use maximum value (you can also pick a random value in [min_val, max_val] for variety)
            val = max_val
            matrix[i][j] = val
            
            # Update remaining sums
            remaining_row[i] -= val
            remaining_col[j] -= val
    
    # Optional: Verify the result (for debugging)
    assert all(sum(row) == 40 for row in matrix), "Generated matrix has invalid row sums"
    assert all(sum(col) == 40 for col in zip(*matrix)), "Generated matrix has invalid column sums"
    assert all(0 <= num <= 8 for row in matrix for num in row), "Matrix elements are out of 0-8 range"
    
    return matrix

示例使用

Let's generate a 5×5 matrix as an example:

sum_rows = [40]*5
sum_cols = [40]*5
matrix = generate_valid_matrix(sum_rows, sum_cols)

# Print the result (each row/column sums to 40, elements are 0-8)
for row in matrix:
    print(row, "Sum:", sum(row))

You'll get a matrix where every element is 8 (since 5×8=40):

[8, 8, 8, 8, 8] Sum: 40
[8, 8, 8, 8, 8] Sum: 40
[8, 8, 8, 8, 8] Sum: 40
[8, 8, 8, 8, 8] Sum: 40
[8, 8, 8, 8, 8] Sum: 40

For a 6×6 matrix, each row will have five 8s and one 0 (5×8+0=40), which also meets all requirements.

补充说明

  • If you want a more "random" matrix, replace val = max_val with val = random.randint(min_val, max_val) (don't forget to import the random module).
  • The assertion checks are optional—they're great for debugging to ensure the matrix is valid, but you can remove them in production code or replace them with friendlier error messages.

内容的提问来源于stack exchange,提问作者2001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:37