c中移矩阵列

发布于 2025-01-27 22:11:09 字数 617 浏览 0 评论 0原文

如何将矩阵的每一列转移到行号左侧? 例如,

 0, 1, 2, 3
 4, 5, 6, 7
 8, 9,10,11
12,13,14,15 

这是一个4*4矩阵,第一行的索引为0,因此列不会移动, 第二行的索引为1,因此每列将向左移动1个斑点(周期性)。 给定矩阵的输出为 示例

我的功能代码是:

void ShiftRows(int message[M][M])
{
    int temp = 0;
    for (int i = 1; i < M ; i++) 
    {
        for (int j = 0; j < M; j++)
        {
            temp = message[i][(j-i)%M];
            message[i][(j-i)%M] = message[i][j];
            message[i][j] = temp;
        } 
        temp = 0;
    }
}

how can i shift each column of a matrix to the left by the row number ?
for example

 0, 1, 2, 3
 4, 5, 6, 7
 8, 9,10,11
12,13,14,15 

this is a 4*4 matrix, the index of the first row is 0, therefore the columns will not move,
the second row's index is 1, therefore each column will move 1 spot to the left (cyclically).
the output for the given matrix is
example

my function code is:

void ShiftRows(int message[M][M])
{
    int temp = 0;
    for (int i = 1; i < M ; i++) 
    {
        for (int j = 0; j < M; j++)
        {
            temp = message[i][(j-i)%M];
            message[i][(j-i)%M] = message[i][j];
            message[i][j] = temp;
        } 
        temp = 0;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

倥絔 2025-02-03 22:11:09

您只交换2个值。这对于周期性移动整个行不起作用。

void ShiftRows(int message[M][M])
{
    for (int i = 1; i < M ; i++) 
    {
        int temp[M];
        // First shift using a copy
        for (int j = 0; j < M; j++)
        {
            temp[j] = message[i][(j+i)%M];
        }

        // After whole row is shifted, copy back
        for (int j = 0; j < M; j++)
        {
            message[i][j] = temp[j];
        } 
    }
}

You only swap 2 values. That does not work for cyclically shift a whole row.

void ShiftRows(int message[M][M])
{
    for (int i = 1; i < M ; i++) 
    {
        int temp[M];
        // First shift using a copy
        for (int j = 0; j < M; j++)
        {
            temp[j] = message[i][(j+i)%M];
        }

        // After whole row is shifted, copy back
        for (int j = 0; j < M; j++)
        {
            message[i][j] = temp[j];
        } 
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文