2015-04-19 16 views
0

我正試圖通過一項任務,要求我在Java中創建一個方法,當給定所需的高度和寬度時,創建一個行或列主矩陣。如何在java中生成行主和列主矩陣?

enter image description here 這是我到目前爲止有:

public static int[][] increasingMatrix(int width, int height, boolean format){ 


     if (format) { // generate row-major matrix 
      int[][] array = new int[height][]; 

      int count = 0; 

      for (int i = 0; i < height; i++) { 
       array[i] = new int[width]; 
       for (int j = 0; j < width; j++) { 
        array[i][j] = count; 
        count++; 
       } 
      } 

      return array; 

     } else { 
      int[][] array = new int[width][]; 


      int count = 0; 

      for (int i = 0; i < width; i++) { 
       array[i] = new int [height]; 
       for (int j = 0; j < height; j++) { 
        array[j][i] = count; 
        count ++; 
       } 
      } 

      return array; 
     } 

    } 

然而,當我去嘗試所產生的陣列上運行測試,列主要矩陣(從我可以告訴)是被生成不正確。行主矩陣似乎正確生成。

你能看到我做錯了什麼嗎?我盯着這幾個小時,但似乎沒有得到任何突破。

謝謝!

回答

1

你的代碼是錯誤的。矩陣中的第一個索引始終是寬度。

記住:矩陣是一個數組數組。第一個索引是矩陣的寬度,第二個索引是高度。

試試這個:

if(format) { 
    return buildRowMajorMatrix(width, height); 
} else { 
    return buildColumnMajorMatrix(width, height); 
} 

凡​​樣子:

private int[][] buildRowMajorMatrix(int width, int height) { 

    int[][] matrix = new int[width][height]; 
    int cellValue = 0; 

    for(int columnIndex = 0 ; columnIndex < width ; columnIndex++) { 
     for(int rowIndex = 0 ; rowIndex < height ; rowIndex++, cellValue++) { 
      matrix[columnIndex][rowIndex] = cellValue; 
     } 
    } 

    return matrix; 
} 

而且buildColumnMajorMatrix樣子:

private int[][] buildColumnMajorMatrix(int width, int height) { 

    int[][] matrix = new int[width][height]; 
    int cellValue = 0; 

    for(int rowIndex = 0 ; rowIndex < height ; rowIndex++) { 
     for(int columnIndex = 0 ; columnIndex < width ; columnIndex++, cellValue++) { 
      matrix[columnIndex][rowIndex] = cellValue; 
     } 
    } 

    return matrix; 
} 
0

在其他條件:

else { 
     int[][] array = new int[width][]; 
     int count = 0; 

     for (int i = 0; i < width; i++) { 
      array[i] = new int [height]; 
      for (int j = 0; j < height; j++) { 
       array[j][i] = count; 
       count ++; 
      } 
     } 

     return array; 
    } 

您試圖嘗試通過數組迭代(矩陣,J-指數的行)還未被初始化。要實現列主矩陣,您需要首先初始化所有行(或切換到更復雜的算法)。

另外我覺得這兩種格式的矩陣的寬度和高度應該是相同的。行列多數只表明我們是否填充矩陣按列或行進行迭代,但我想這個任務的措辭留下了解釋空間。

我的解決辦法:

public static int[][] increasingMatrix(int width, int height, boolean format){ 
    int[][] array = new int[height][width]; // Java's shortcut generating regular array of arrays for you 
    int count = 0; 
    if (format) { // generate row-major matrix 
     for (int i = 0; i < height; i++) { 
      for (int j = 0; j < width; j++) { 
       array[i][j] = count; 
       count++; 
      } 
     } 
    } else { 
     for (int j = 0; j < width; j++)) { 
      for (int i = 0; i < height; i++ { 
       array[i][j] = count; 
       count++; 
      } 
     } 
    } 

    return array; 
}