Creating a 2d matrix from an array (java)

Posted by anna on Stack Overflow See other posts from Stack Overflow or by anna
Published on 2010-04-24T23:16:48Z Indexed on 2010/04/24 23:23 UTC
Read the original article Hit count: 177

Filed under:
|
|
|

I'm supposed to write a method that creates a 2d matrix from an array, for instance: ({1, 2, 3, 4}, 3) should return the matrix {{1, 2, 3}, {4}}

public class Matrix {
  public static int[][]toM(int[] array, int a) {
    int[][]matrix = new int [(array.length + a- 1)/ a][a];
    for (int i = 0; i < array.length; i++){
      int value = array[i];
      value = value++;
      for (int row = 0; row < (array.length + a- 1)/a; row++) {
        for (int col = 0; col < a; col++) {
          matrix[row][col]= value++;
        }
      } 
    }
    return matrix;
  }
}

I'm getting [[4, 5, 6], [7, 8, 9]]?

© Stack Overflow or respective owner

Related posts about java

Related posts about array