收到的值不是期望的结果
values received are not the desired result
我有一个名为 gMul
的锯齿状数组,其中有 4 个数组,我想将第一个和所有其他等于该数组的数组移动 n 次(n 代表它们在锯齿状数组中的索引)
最后一个数组由于某种原因等于它之前的数组,例如:
gMul[0] = new byte[] {2 , 3 , 2 , 2}
那么结果应该是
gMul[0] - {2 , 3 , 2 , 2}
gMul[1] - {2 , 2 , 3 , 2}
gMul[2] - {2 , 2 , 2 , 3}
gMul[3] - {3 , 2 , 2 , 2}
但出于某种原因,我得到的结果是这样的:
gMul[0] - {2 , 3 , 2 , 2}
gMul[1] - {2 , 2 , 3 , 2}
gMul[2] - {2 , 2 , 2 , 3}
gMul[3] - {2 , 2 , 2 , 3}
我的代码:
for (int i = 1; i < gMul.GetLength(0); i++)
{
//shift is a function that shifts the given array one item to the right
//and returns an array of bytes
byte[] shifted = shift(gMul[i - 1]);
gMul[i] = shifted;
}
public byte[] shift(byte[] row)
{
byte tmp = row[0];
for (int i = row.Length - 1; i >= 0; i--)
{
row[(i + 1) % row.Length] = row[i];
}
row[1] = tmp;
return row;
}
移位算法有问题。正确的算法是这个
public byte[] ShiftRight(byte[] row)
{
var newRow = new byte[row.Length];
byte tmp = row[row.Length - 1];
for(int i = row.Length - 1; i > 0; i--)
{
newRow[i] = row[i - 1];
}
newRow[0] = tmp;
return newRow;
}
或者直接使用Array.Copy.
public byte[] ShiftRight(byte[] row)
{
var newRow = new byte[row.Length];
byte tmp = row[row.Length - 1];
Array.Copy(row, 0, newRow, 1, row.Length - 1);
newRow[0] = tmp;
return newRow;
}
我有一个名为 gMul
的锯齿状数组,其中有 4 个数组,我想将第一个和所有其他等于该数组的数组移动 n 次(n 代表它们在锯齿状数组中的索引)
最后一个数组由于某种原因等于它之前的数组,例如:
gMul[0] = new byte[] {2 , 3 , 2 , 2}
那么结果应该是
gMul[0] - {2 , 3 , 2 , 2}
gMul[1] - {2 , 2 , 3 , 2}
gMul[2] - {2 , 2 , 2 , 3}
gMul[3] - {3 , 2 , 2 , 2}
但出于某种原因,我得到的结果是这样的:
gMul[0] - {2 , 3 , 2 , 2}
gMul[1] - {2 , 2 , 3 , 2}
gMul[2] - {2 , 2 , 2 , 3}
gMul[3] - {2 , 2 , 2 , 3}
我的代码:
for (int i = 1; i < gMul.GetLength(0); i++)
{
//shift is a function that shifts the given array one item to the right
//and returns an array of bytes
byte[] shifted = shift(gMul[i - 1]);
gMul[i] = shifted;
}
public byte[] shift(byte[] row)
{
byte tmp = row[0];
for (int i = row.Length - 1; i >= 0; i--)
{
row[(i + 1) % row.Length] = row[i];
}
row[1] = tmp;
return row;
}
移位算法有问题。正确的算法是这个
public byte[] ShiftRight(byte[] row)
{
var newRow = new byte[row.Length];
byte tmp = row[row.Length - 1];
for(int i = row.Length - 1; i > 0; i--)
{
newRow[i] = row[i - 1];
}
newRow[0] = tmp;
return newRow;
}
或者直接使用Array.Copy.
public byte[] ShiftRight(byte[] row)
{
var newRow = new byte[row.Length];
byte tmp = row[row.Length - 1];
Array.Copy(row, 0, newRow, 1, row.Length - 1);
newRow[0] = tmp;
return newRow;
}