2016-06-15 118 views

回答

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

     } 
    } 
}