2016-06-15 5 views
-3

私は3x3マトリックスを持っています そのマトリックスを2x2マトリックスに印刷したい 例:5x5マトリックスをすべて2 * 2に出力可能サブマトリックス

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

最初にコード/回避方法を共有してください。 –

+1

あなたはどの言語を使用していますか?あなたとコードを投稿するpls – Thomas

答えて

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; 
      } 

     } 
    } 
} 
関連する問題