3 回答
TA贡献1777条经验 获得超10个赞
我知道您正在尝试使用递归,但是使用 LINQ 进行此练习要简单得多。
如果你从这个开始:
int[,] twoDArr = new int[,]
{
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 },
};
int[][]通过这样做可以很容易地将其转换为 a :
int[][] rows =
twoDArr
.Cast<int>() // flattens to one dimension
.Select((value, index) => new { value, index })
.GroupBy(x => x.index / twoDArr.GetLength(1), x => x.value)
.Select(x => x.ToArray())
.ToArray();
在.GroupBy关键的是x.index / twoDArr.GetLongLength(1),这样的从零开始的每一行的整数。
这给出了:
现在你可以简单地这样做:
int result = rows.First().Sum() + rows.Last().Sum();
我从我的样本数据中得到的结果是18
(这是第一行和最后一行的正确总和)。
TA贡献1852条经验 获得超7个赞
这与您的代码无关。这只是我对第一行和最后一行进行递归求和的版本。我希望它有帮助。
int SumFirstLastRows(int[,] twoD)
{
// we need some pointer information on when to start and end,
// let's use column and row number, starting from 0,0
return SumRecursive(twoD, 0, 0);
}
// this is a recursive method, which goes for each row and column recursively,
// however it only takes the sum of first and last rows' numbers
int SumRecursive(int[,] twoD, int column, int row)
{
// determine the max row and column, to know when to end
int maxRows = twoD.GetLength(0);
int maxColumns= twoD.GetLength(1);
if (row == maxRows)
{
// we are at the end of the rows, end everything
return 0;
}
else if (column == maxColumns)
{
// we are at the end of column, switch to the next row instead
return SumRecursive(twoD, 0, row + 1);
}
if ((row== 0 || row == maxRows-1) && column < maxColumns)
{
// only for the first or last row: current number + next column sum
return twoD[row, column] + SumRecursive(twoD, column + 1, row);
}
else if(column < maxColumns)
{
// not the first or last row, so just skip to the next column
return SumRecursive(twoD, column + 1, row);
}
return 0;
}
测试:
int[,] twod = new int[3,4]
{ {1,2,3,4 },
{5,6,7,8 },
{9,10,11,12 }
};
int recursiveTest = SumFirstLastRows(twod);
int forVerification = 1 + 2 + 3 + 4 + 9 + 10 + 11 + 12;
bool isThisCorrect = recursiveTest == forVerification; // return true!
- 3 回答
- 0 关注
- 244 浏览
添加回答
举报