java将矩阵旋转45度输出

来源:互联网 发布:linux重新识别hba卡 编辑:程序博客网 时间:2024/05/29 03:25

例如:

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;    }}
0 0
原创粉丝点击