Transposing a matrix from a 2D array

后端 未结 5 2109
借酒劲吻你
借酒劲吻你 2021-01-06 19:38

I\'m self teaching myself some java and I\'m stuck on creating a 2D array that initializes it with random values and then creates the transpose of the array.

An ex

5条回答
  •  既然无缘
    2021-01-06 20:30

    You can use the below class it has most of the methods you want.

    /**
     * Class representing square matrix of given size.
     * It has methods to rotate by 90, 180 and 270
     * And also to transpose and flip on either axis.
     * 
     * I have used both space efficient methods in transpose and flip
     * And simple but more space usage for rotation. 
     * 
     * This is using builder pattern hence, you can keep on applying
     * methods say rotate90().rotate90() to get 180 turn.
     * 
     */
    public class Matrix {
    
        private int[][] matrix;
        final int size;
    
        public Matrix(final int size) {
            this.size = size;
            matrix = new int[size][size];
    
            for (int i=0;i 3) {
                        sb.append("\t");
                    }
                }
                sb.append("|\n");
            }
    
            return sb.toString();
        }
    
        public static void main(String... args) {
            Matrix m = new Matrix(3);
            System.out.println(m);
    
            //transpose and flipHorizontal is 270 turn (-90)
            System.out.println(m.transpose());
            System.out.println(m.flipHorizontal());
    
            //rotate 90 further to bring it back to original position
            System.out.println(m.rotate90());
    
            //transpose and flip Vertical is 90 degree turn
            System.out.println(m.transpose().flipVertical());
        }
    }
    

    Output:

    |0|1|2|
    |3|4|5|
    |6|7|8|
    
    |0|3|6|
    |1|4|7|
    |2|5|8|
    
    |2|5|8|
    |1|4|7|
    |0|3|6|
    
    |0|1|2|
    |3|4|5|
    |6|7|8|
    
    |6|3|0|
    |7|4|1|
    |8|5|2|
    

提交回复
热议问题