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

如何在C语言中分割二维数组的行?含跨行连续值计数需求

Solution for Per-Row Consecutive Non-Zero Element Counting

Got it, let's fix the issue where your code was incorrectly merging consecutive elements across rows. The key here is to process each row independently—so we never carry over counts from one row to the next, even if the last element of a row matches the first of the next.

Step 1: Clarify the Input Structure

First, let's convert your flat input list into the 4x6 2D array as specified:

width = 6
height = 4
input_elements = [0, 1, 2, 2, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0]
# Split into 4 rows of 6 elements each
matrix = [input_elements[i*width : (i+1)*width] for i in range(height)]

This gives us the clear 2D structure:

  • Row 1: [0, 1, 2, 2, 1, 0]
  • Row 2: [1, 0, 0, 0, 0, 1]
  • Row 3: [1, 0, 0, 0, 0, 1]
  • Row 4: [0, 1, 1, 1, 1, 0]

Step 2: Per-Row Counting Function

We'll write a function that counts consecutive non-zero elements only within a single row, resetting the count at the start of each row:

def count_consecutive_non_zero(row):
    counts = []
    current_streak = 0
    for num in row:
        if num != 0:
            current_streak += 1
        else:
            # When we hit a 0, save the streak if it's non-zero
            if current_streak > 0:
                counts.append(current_streak)
                current_streak = 0
    # Don't forget to save the streak if the row ends with non-zero
    if current_streak > 0:
        counts.append(current_streak)
    return counts

Step 3: Generate the Desired Output

Loop through each row and apply the function:

for idx, row in enumerate(matrix, 1):
    result = count_consecutive_non_zero(row)
    # Format as space-separated string
    print(f"第{idx}行:{' '.join(map(str, result))}")

Final Output

Running this code will give you exactly what you're expecting:

  • 第1行:1 2 1
  • 第2行:1 1
  • 第3行:1 1
  • 第4行:4

Why This Fixes the Cross-Row Issue

The mistake in your original code was likely keeping the current_streak variable outside the row loop—so it would keep counting from the end of one row to the start of the next if the values matched. By initializing current_streak inside the function (per row), we ensure each row starts fresh, with no leftover counts from previous rows.

内容的提问来源于stack exchange,提问作者승기유

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:01:07