【问题标题】:How to delete a consecutive duplicate row in C matrix?如何删除C矩阵中连续的重复行?
【发布时间】:2020-12-24 18:04:08
【问题描述】:

我想删除矩阵中的连续行。例如: 我的矩阵有 3 行 3 列。 矩阵的元素是:
1 2 3
1 2 3
4 5 6
对于此示例,输出应为:
1 2 3
4 5 6

我已经尝试了一个实现,但我遇到了一些问题,我知道我必须使用另一个矩阵,其行必须被修改,但到目前为止我没有任何正确的结果。

我怎样才能让它工作?

#include <stdio.h>
#include <stdlib.h>

void readMatrix(int matrix[100][100], int noRows, int noCol);
void removeLine(int matrix[100][100], int noRows, int noCol);
void printMatrix(int matrix[100][100], int noRows, int noCol);

int main()
{
    int noRows, noCol, matrix[100][100], i, j;

    printf("n="); scanf("%d", &noRows);
    printf("m="); scanf("%d", &noCol);

    readMatrix(matrix, noRows, noCol);
    printMatrix(matrix, noRows, noCol);

    return 0;
}

void removeLine(int matrix[100][100], int noRows, int noCol)
{
    int i, j;
    int temp[100][100];
    for (i = 0; i < noRows - 1; i++)
        for (j = 0; j < noCol; j++)
        {
            if (matrix[i][j] == temp[i + 1][j])
            {
                matrix[i][j] == temp[i + 1][j];

            }
        }
}

void readMatrix(int matrix[100][100], int noRows, int noCol)
{
    int i, j;

    for (i = 0; i < noRows; i++)
        for (j = 0; j < noCol; j++)
        {
            printf("\na[%d][%d]=", i, j); scanf("%d", &matrix[i][j]);
        }
}

void printMatrix(int matrix[100][100], int noRows, int noCol)
{
    int i, j;
    for (i = 0; i < noRows; i++)
    {
        for (j = 0; j < noCol; j++)
        {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

【问题讨论】:

  • 描述没有说明问题是什么。
  • 您不能从数组中删除行。您可以复制一行之后的所有行以删除左一个位置。
  • 这看起来像 C++,但您已将其标记为 C。请修复。
  • @MYousefi 我编辑了它,但我认为很明显问题是我无法让它工作

标签: c matrix


【解决方案1】:

您不能从二维数组中删除行。您可以向左移动行:

// Helper function to "delete" one row from the array
void deleteRow(int matrix[100][100], int row, int noRows, int noCol)
{
    // Copy all rows after row to one row over
    for (int i = row; i < noRows - 1; i++) {
        // Use memcpy to copy entire row
        memcpy(matrix[i], matrix[i+1], sizeof(int) * noCol);
    }
}

// Remove repeats
void removeLines(int matrix[100][100], int *noRows, int noCol)
{
    for (int i = 0; i < *noRows - 1; i++) {
        // Use memcmp to compare entire row
        if (memcmp(matrix[i], matrix[i + 1], sizeof(int) * noCol) == 0) {
             deleteRow(matrix, i+1, *noRows, noCol);
             i -= 1;
             *noRows -= 1;
        }
    }
}

这里有优化的空间——尤其是重复次数超过 1 次时。

【讨论】:

  • 我在尝试运行代码时遇到了异常。“抛出未处理的异常:读取访问冲突。noRows 为 0x3。”
  • @Leobej 请注意,我将值更改为指针。您也可以将其保留为 int 并让函数返回新的行数。
  • 这个答案会留下最后一行和前一行的重复行。
  • @user3629249 是的,正如我在答案中提到的,您不能删除一行,只能覆盖。但是该函数会根据“删除”的行数修改noRows 变量。
猜你喜欢
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 2017-01-09
  • 2011-10-13
  • 2018-08-11
  • 1970-01-01
相关资源
最近更新 更多