您的位置:首页 > 编程语言 > Java开发

java将矩阵旋转45度输出

2015-07-31 08:38 369 查看
例如:

A B C D E
F G H I J
K L M N O
P Q R S T
U V W X Y
E
D J
C I O
B H N T
A G M S Y
F L R X
K Q W
P V
U




思路如上图:

在菱形之外的都是空格,菱形之内(可以使用函数判断)有两种点,一种是有字符,一种是空格

可以发现,有字符的位置(col-row)%2 == 0;接下来寻找45度菱形和矩形的对应关系,row’=(col-row)/2 ,col’=col-row’

完整代码如下:

public class PrintMatrixTrans45degree
{
public static void main(String[] args)
{
System.out.println("Hello World!");
int c=0;
char[][] arr = new char[5][5];
for(int i = 0 ; i < 5; i++){
for(int j = 0; j < 5; j ++){
arr[i][j]= (char)('A' + c);
c++;
}
}
for(int i = 0 ; i < 5; i++){
for(int j = 0; j < 5; j ++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
for(int i = 4; i >= -4; i--){
int row = 0;
int col = 0;
for(int j = 0; j <= 8 ; j ++){
if(isArea(i,j)){
if((j-i)%2 == 0){
//打印字母
row = (j - i)/2;
col = j - row;
System.out.print(arr[row][col]);
}else{
System.out.print(" ");
}
}else{
//打印空格
System.out.print(" ");
}
}
System.out.println();
}
}

public static boolean isArea(int row , int col){
if(row <= col &&  row >= col - 8 && row >= -col && row <= -col + 8  ){
//System.out.println("("+row+","+col+")");
return true;
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: