将5x5矩阵打印到所有2 * 2个可能的子矩阵中

时间:2016-06-15 06:28:24

标签: arrays

我有一个3x3矩阵, 我想将该矩阵打印成2x2矩阵 例如。

2 5 3 
5 8 9
1 4 5

来到2 * 2矩阵

2 5 
5 8

5 8 
1 4

5 3 
8 9

8 9 
4 5

怎么做?

1 个答案:

答案 0 :(得分:0)

import java.util.*;

/**
 * This MatrixCombination used to read matrix values and to print possible
 * combination of sub mat rix Author: Gopikrishna
 */
public class MatrixCombinations {
    // Created a object to Scanner class
    static Scanner sc = new Scanner(System.in);

    // valueReader method splits given string and returns two dimensional array
    // back
    // to main method
    public String[][] valueReader(String str) {
        String[] rows = str.split(",");

        String[][] matrix = new String[rows.length][];
        int columns = 0;
        for (String row : rows) {
            matrix[columns++] = row.split("#");
        }
        // nested for each loop to print matrix values
        for (String temp[] : matrix) {
            for (String var : temp) {
                System.out.print("\t" + var);
            }
            System.out.println("");
        }
        return matrix;
    }

    public static void main(String args[]) {
        int rIndex = 0, cIndex = 0;
        MatrixCombinations t = new MatrixCombinations();
        System.out
                .println("Enter String # as element seperator and , as row seperator");
        System.out
        .println("please matain same number of column elements for each row ");
        String str = sc.nextLine();
        String arr[][] = t.valueReader(str);
        int row = arr.length;
        int col = arr[0].length;
        // asking sub matrix rows and columns
        System.out.println("Enter sub rows");
        int srow = sc.nextInt();
        System.out.println("Enter sub columns");
        int scol = sc.nextInt();
        System.out.println("Possible combinations are ");
        while (true) {
            while ((srow <= row - rIndex) && (scol <= col - cIndex)) {

                // rowBoundary and colBoundary variables are boundarys to print values 

                int rowBoundary = srow + rIndex;
                int colBoundary = scol + cIndex;
                for (int i = rIndex; i < rowBoundary; i++) {
                    for (int j = cIndex; j < colBoundary; j++) {
                        System.out.print("  " + arr[i][j]);
                    }
                    System.out.println();
                }
                rIndex++;
                System.out
                        .println("-----------------------------------------------------");
            }
            rIndex = 0;
            cIndex++;
            //if subColumns not avalible stop the loop
            if (scol > col - cIndex) {
                break;
            }

        }
    }
}