【问题标题】:Two-Dimension array value replace with array二维数组值替换为数组
【发布时间】:2017-05-04 01:45:00
【问题描述】:

我正在使用 C#。我想用另一个二维数组替换二维数组中的值。

数组要替换的值是

{
    {100, 100, 100, 100},
    {100, 100, 100, 100},
    {100, 100, 100, 100},
    {100, 100, 100, 100}
}

并且,某个数组要替换该数组的值是什么

{
    {500,500},
    {500,500}
}

我期待:

{
    {100,100,100,100},
    {100,500,500,100},
    {100,500,500,100},
    {100,100,100,100}
}

【问题讨论】:

  • 如果您希望获得帮助,您需要发布您的代码。
  • 这背后的逻辑是什么?

标签: c# arrays replace


【解决方案1】:

简单易懂的带有两个循环的代码:

var bigger = new int[,]
{
    {100, 101, 102, 103, 104},
    {100, 100, 100, 100, 100},
    {100, 100, 100, 100, 100},
    {100, 100, 100, 100, 100},
};

var smaller = new int[,]
{
    {1, 2},
    {3, 4},
};

ReplaceValues (bigger, smaller, 3, 2);

和静态方法:

public static void ReplaceValues (int[,] destinationArray, int[,] replaceWith, int columnOffset, int rowOffset)
{
    for (int row = 0; row < replaceWith.GetLength (0); row++)
    {
        for (int column = 0; column < replaceWith.GetLength (1); column++)
        {
            destinationArray[row + rowOffset, column + columnOffset] = replaceWith[row, column];
        }
    }
}

当然,您应该根据您的要求升级此代码。

结果:

【讨论】:

    【解决方案2】:

    在这种情况下,您需要比较这些数组的维度: 大数组是:4x4,小数组是 2x2(双)。所以循环遍历大数组是:

    bigarray[i x 2 + 1, j x 2 + 1] = smallarray [i,j].
    

    所以公式可以是:

    bigarray[i x compare_value + 1, j x compare_value + 1] = smallarray [i,j]
    

    compare_value = bigarray/ smallaray

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 2013-11-25
      • 1970-01-01
      相关资源
      最近更新 更多