C# 按以下格式打印给定数字的矩阵
对于给定的数字C# 按以下格式打印给定数字的矩阵,c#,C#,对于给定的数字n我必须打印以下矩阵(n=3示例): 行和列的计数应为(2*n)-1。我试着找出那个模式,但没能找到。任何帮助都会有帮助。谢谢诸如此类的东西: private static int[][] Matrix(int n) { // Create arrays int[][] result = Enumerable.Range(0, 2 * n - 1) .Select(_ => new int[2 * n - 1]) .ToArray(); // F
n
我必须打印以下矩阵(n=3
示例):
行和列的计数应为(2*n)-1
。我试着找出那个模式,但没能找到。任何帮助都会有帮助。谢谢诸如此类的东西:
private static int[][] Matrix(int n) {
// Create arrays
int[][] result = Enumerable.Range(0, 2 * n - 1)
.Select(_ => new int[2 * n - 1])
.ToArray();
// Feed arrays
for (int i = 1; i <= n; ++i) {
int from = i - 1;
int to = 2 * n - i - 1;
int v = n - i + 1;
for (int j = from; j <= to; ++j) {
result[from][j] = v;
result[to][j] = v;
result[j][from] = v;
result[j][to] = v;
}
}
return result;
}
....
int n = 3;
String report = String.Join(Environment.NewLine, Matrix(n)
.Select(line => String.Join(" ", line)));
Console.Write(report);
对于n=4
:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
这是一个不使用任何中间存储的版本:
static void printMatrix(int n)
{
int x = 2*n - 1;
for (int i = 0, p = n; i < x; ++i, p += (i > x/2) ? 1 : -1)
{
for (int j = 0, q = n; j < x; ++j, q += (j > x/2) ? 1 : -1)
Console.Write(Math.Max(p, q) + " ");
Console.WriteLine();
}
}
静态无效打印矩阵(int n)
{
int x=2*n-1;
对于(inti=0,p=n;ix/2)?1:-1)
{
对于(intj=0,q=n;jx/2)?1:-1)
Console.Write(Math.Max(p,q)+”);
Console.WriteLine();
}
}
这项工作如下:
外环(i)和内环(j)都从0开始。。2*n-1
但是,我们要打印的值(p
和q
)从n
开始,一直减小到矩阵的一半,然后开始再次增大
我们可以通过检查循环变量来确定是增加还是减少这些值,以查看它是否在矩阵的中间。如果是,我们减少,否则我们增加
这就是它所做的:p+=(i>x/2)?1:-1
如果i>x/2
则值1
将用于增量,否则-1
将用于增量(即,将递减)
(类似于q
)
最后一个难题是,我们想要使用的值实际上是p
和q
的最大值。如果检查矩阵,则会看到,如果考虑每个行值和每个列值,则每个值的最大值用于相应的单元格。
因此,在输出中使用了
Math.Max(p,q)
。这里有一个更简单的解决方案,目前为止不太复杂,速度最快:
private static void printMatrix(int n)
{
// length of the matrix in one dimension
int length = (2 * n) - 1;
// iterate through y axis of the matrix
for (int i = 0; i < length; i++)
{
int value = n;
// iterate through x axis of the matrix
for (int j = 0; j < length; j++)
{
Console.Write(value);
if (i > j && i + j < length - 1)
{
value--;
}
else if (i <= j && i + j >= length - 1)
{
value++;
}
}
Console.WriteLine();
}
}
如您所见,该值仅在特定情况下更改
如果i>j
和i+j
,这会发生-1
,否则在索引3,1
之后,您将有错误的值,之后不应该再减去该值。
这两条if语句引导我们找到代码中的第一条语句:
if (i > j && i + j < length - 1)
{
value--;
}
else if (i <= j && i + j >= length - 1)
{
value++;
}
如果这些语句都不是真的,则值将保持不变。使用多维int数组创建具有特定行-列顺序的二维矩阵,然后使用给定条件赋值并打印结果。只需显示您的代码,我们会检查它。@Tetsuya Yamamoto:锯齿数组(即数组数组
int[][]]
)而不是2D数组(int[,]
)可以做得更好。您能解释一下吗?@SillyVolley当然,我会对答案添加注释。@SillyVolley看一下我的解释。正如我在解释中所做的那样,这确实有助于我写一篇论文并记下这些值。请随时询问是否还有不清楚的地方。
// +1 and -1 means the changes of the values
0,0 0,1 0,2 0,3 0,4 // values of i,j (first is i, second is j)
[3] [3] [3] [3] [3] // printed value
1,0 1,1 1,2 1,3 1,4
[3] -1 [2] [2] [2] +1 [3]
2,0 2,1 2,2 2,3 2,4
[3] -1 [2] -1 [1] +1 [2] +1 [3]
3,0 3,1 3,2 3,3 3,4
[3] -1 [2] [2] [2] +1 [3]
4,0 4,1 4,2 4,3 4,4
[3] [3] [3] [3] [3]
if (i > j && i + j < length - 1)
{
value--;
}
else if (i <= j && i + j >= length - 1)
{
value++;
}