c - 将所有非空元素向左移动

标签 c sorting matrix

如果元素为 0,则必须向左移动。我尝试了一个从 2D 矩阵数组末尾开始的循环,但我似乎无法理解为什么它不起作用。

输入范围必须在 -999 到 999 之间。

我将 != 0 的元素分配给第一个索引,然后如果必须将该临时整数向前移动一步。这是我的主要问题,因为我无法解决这个问题。也许需要不同的方法?

(我试图在没有指针的情况下解决它)

int main()
{
    int M[3][3];
    int j = 0;
    int i = 0;

    for(i = 0; i < 3; ++i){
        for(j = 0; j < 3; ++j){
            printf("Give me the number for [%d][%d]: ", i, j);
            scanf("%d", &M[i][j]);

            if(-999 > M[i][j] || M[i][j] > 999) j--;
            // a)
            if((i + j) % 2 == 0) {
                M[i][j] = 0;
            }

        }
    }
    // Print the result of a) 
    for(i = 0; i < 3; ++i){
        for(j = 0; j < 3; ++j){
            printf("%d ", M[i][j]);
        }
        printf("\n");
    }

    // Shifting the elements to the left  b)
    int temp = M[0][0];
    for(i = 2; i >= 0; i--)
    {
        for(j = 2; j >= 0; j--){
            if(M[i][j] != 0)
            {
                M[i][j] = temp;
            }
            // change the value of temp
        }
    }
    // Print the array after a) and b)
    for(i = 0; i < 3; ++i){
        for(j = 0; j < 3; ++j){
            printf("%d ", M[i][j]);
        }
    }
}

a)的结果就是第一步后的矩阵,其中if (i=j)将该处的值转换为0。

例如,如果您输入:1 2 3 4 5 6 7 8 9
结果将是: 0 2 0 4 0 6 0 8 0
b) 的最终结果尚未完成,但应如下所示: 2 4 6 8 0 0 0 0 0。

最佳答案

Perhaps a different approach is wanted?

由于 [3][3] 数组在内存中与 [1][3*3] 数组类似,因此只需简单移位 M[0] 就好像它有 9 个元素一样。

unsigned nonzero_index = 0;
for(i = 0; i < 3*3; ++i){
  if (M[0][i]) {
    M[0][nonzero_index++] = M[0][i];
  }
}
while (nonzero_index < 3*3) { //  zero fill the rest
  M[0][nonzero_index++] = 0;
}

关于c - 将所有非空元素向左移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57943114/

相关文章:

python - 选择矩阵 pandas python 上的最高行。

r - 从现有矩阵构建 block 矩阵并在 r 中保留暗名称

Postgresql 中的 C 库函数

c - 使用常量结构时为 "initializer element is not constant"

powershell - 在输出前使用 Get-FileHash 对 Get-ChildItem 的结果进行排序

javascript - 使用后续数据结果重新排序 angularjs ngRepeat

python - 在矩阵中设置值 - Python

c - 为什么 clang 找不到 unixodbc 函数的符号?

c - 为什么 TCP 服务器套接字意外关闭?

c# - 使用 Excel Interop C# 对 Excel 行进行排序