【发布时间】:2020-10-05 14:16:31
【问题描述】:
【问题讨论】:
-
...关于我们如何从二维数组到该图片的规则是什么?给我们更多的解释。到目前为止,您尝试过什么?
标签: c# arrays matrix multidimensional-array
【问题讨论】:
标签: c# arrays matrix multidimensional-array
我认为这是沿其主对角线打印的。
.
在示例案例中,我们列出了arr2d 的索引:
(0, 2)
(0, 1), (1, 2)
(0, 0), (1, 1), (2, 2)
(1, 0), (2, 1)
(2, 0)
看到常规模式了吗?
x保持0,y减少。 y 保持为 0,x 增加。(x++, y++),直到x 或y ≥3。对于更一般的方式,n 维矩阵具有2n-1 三角形线。
n 行中,第一个元素的x 保留为0,y 减少。 n 行中,第一个元素的y 保留为0,x 增加。 (x++, y++) 直到 x 或 y ≥3。代码如下:
static void Main(string[] args) {
int[,] arr2d = new int[3,3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int dimension = 3;
int x = 0, y = dimension - 1
while(y >= 0) {
WriteDiagalNumbers(arr2d, x, y, dimension);
y--;
// or shorten as
// WriteDiagalNumbers(arr2d, x, y--, dimension);
}
x = 1;
y = 0;
while(x < dimension) {
WriteDiagalNumbers(arr2d, x, y, dimension);
x++;
// or shorten as
// WriteDiagalNumbers(arr2d, x++, y, dimension);
}
}
static void WriteDiagalNumbers(int[,] arr, int x, int y, int dimension) {
List<int> nums = new List<int>();
while(x < dimension && y < dimension) {
nums.Add(arr[x, y]);
x++;
y++;
// or shorten as
// nums.Add(arr[x++, y++]);
}
Console.WriteLine(string.Join(", ", nums));
}
给出输出:
3
2, 6
1, 5, 9
4, 8
7
【讨论】:
我喜欢 Sheey 的回答,尽管数组维度在该解决方案中是硬编码的,这让我很困扰。所以这里有一个通用的方法,使用GetUpperBound() 来确定行数/列数。
调用GetUpperBound(0) 会告诉您有多少ROWS,而GetUpperBound(1) 会给出COLUMNS 的数量。
我们可以从数组的右上角开始向左移动,得到所有对角线起始位置的坐标。一旦我们击中左侧,我们就会沿着阵列向下移动。从这些起始位置中的每一个,我们通过增加两个起始 x/y 位置来获得对角线值,而它们都在数组的范围内。这是可以使用具有多个变量的 for 循环的少数情况之一。
代码还根据最大值填充输出,以便三角形可以处理任何大小的整数。
请注意,当访问二维数组时,x 和 y 参数是相反的:
arr[y, x]
您将y 值列为第一个参数,将x 值列为第二个参数。
所以有了这个数组:
int[,] arr2d = new int[,]
{
{85, 86, 87, 88},
{89, 90, 91, 92},
{93, 94, 95, 96},
{97, 98, 99, 100}
}
88 值,使用从零开始的表示法,通常被认为是坐标 (2, 0),但可以使用 arr2d[0, 2] 访问。
同样,97 值通常被认为是坐标 (0, 2),但可以通过 arr2d[2, 0] 访问。
我觉得这种方法足够不同,足以保证对这个问题提供额外的答案:
static void Main(string[] args)
{
int[,] arr2d = new int[,]
{
{85, 86, 87, 88},
{89, 90, 91, 92},
{93, 94, 95, 96},
{97, 98, 99, 100}
};
printTriangle(arr2d);
Console.Write("Press Enter to quit...");
Console.ReadLine();
}
static void printTriangle(int[,] arr)
{
// Get all the starting positions for "diagonals":
// Start in the top right of the array,
// then move all the way left,
// followed by all the way down.
int y = 0;
int x = arr.GetUpperBound(1);
bool travelLeft = true;
bool triangleComplete = false;
List<string> diagonalValues = new List<string>();
int pad = arr.Cast<int>().Max().ToString().Length;
while (!triangleComplete)
{
diagonalValues.Clear();
for(int yTemp = y, xTemp = x;
xTemp <= arr.GetUpperBound(1) && yTemp <= arr.GetUpperBound(0);
xTemp++, yTemp++)
{
diagonalValues.Add(arr[yTemp, xTemp].ToString().PadLeft(pad));
}
Console.WriteLine(String.Join(", ", diagonalValues));
if (travelLeft)
{
x--; // move left
travelLeft = (x > 0);
}
else
{
y++; // move down
triangleComplete = (y > arr.GetUpperBound(1));
}
}
}
输出:
88
87, 92
86, 91, 96
85, 90, 95, 100
89, 94, 99
93, 98
97
Press Enter to quit...
【讨论】: