我想构造一个大小为 n 的方阵(2D)(将由用户输入) 现在我想构造一个对角线图案。 例如(3X3 矩阵):
2 3
1
4 5
value
变量将被初始化为 1 并存储在方阵的中心。然后 value
将递增并存储在左上角,如上所示,依此类推。
这是一个在控制台上显示的简单程序。 用户输入可以从命令行获取。 我试图概括 for 循环中的一个条件,该条件适用于大小为 5,7,9...(奇数)的方阵。 对于大小为 5 的矩阵,它将是
6 7
2 3
1
4 5
8 9
(空格可以为零)
我的代码:
import java.util.*;
public class MatrixAdv
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Please enter size of element...");
int n=sc.nextInt(); //stores size of Matrix
int value=0; //To be incremented everytime to get the Pattern
int [][] matrix = new int[n][n];
int k=0;
for(int i=0;i<some Condition;i++)
{
for(int j=1;j<some Condition;j++)
{
k=n-2-j;
matrix[k][k]=++value;
}
}
}
//Display the value in matrix form
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
Print(matrix[i][j]+"\t");
}
Print("\n");
}
}
最佳答案
如果您了解矩阵的魔力,那么打印 99% 的矩阵图案非常容易......并且无需使用任何内存即可完成。
这是代码......
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
if(n == 1)
cout<<1;
else
{
int sv=2*n-4,a,b;
a=sv;b=sv+1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i == j && i+j == n+1)
{
cout<<" 1 ";
sv=4;
}
else
{
if(i == j)
cout<<" "<<a<<" ";
else if((i+j) == n+1)
cout<<" "<<b<<" ";
else
cout<<" ";
}
}
if(i < n/2+1)
{
sv=sv-4;
a=sv;b=sv+1;
}
else if(i > n/2+1)
{
sv=sv+4;
b=sv;a=sv+1;
}
else
{
sv=4;
b=sv;a=sv+1;
}
cout<<"\n";
}
}
}
关于java - 显示矩阵以获得独特的图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22200234/