Creating a 2d matrix from an array (java)

29,419

Solution 1

Your code is a little too far off base to easily repair. For starters, a three-level nested loop is completely unnecessary; also, you don't fetch array elements by writing value++ (maybe you are getting confused with the C convention of using *ptr++ to walk an array). Start again from first principles.

I'm assuming this is homework, so I'm not going to just write it for you. But here's the basic outline. The number of result elements depends on the input array rather than the dimensions of the output matrix, so your algorithm should loop over the input elements. For each element, some basic math on its index, i, will tell you where it belongs (row and col) in the output matrix. Assign array[i] to matrix[row][col].

For bonus points, note that the last row is often shorter than the other rows. Allocating matrix = new int [...][a] will produce [[1, 2, 3], [4, 0, 0]] instead of the stated requirement. Fix this by allocating just the outer array of arrays — matrix = new int [...][] — and allocating each sub-array individually, making a special case of the last row using modulus arithmetic.

Solution 2

I think something like this is a lot more readable:

static int[][] transform(int[] arr, int N) {
    int M = (arr.length + N - 1) / N;
    int[][] mat = new int[M][];
    int start = 0;
    for (int r = 0; r < M; r++) {
        int L = Math.min(N, arr.length - start);
        mat[r] = java.util.Arrays.copyOfRange(arr, start, start + L);
        start += L;
    }
    return mat;
}

Your resulting matrix will be MxN, with the last row possibly having less. It uses Arrays.copyOfRange instead of manually allocating and copying rows, and some math to figure out M (how many rows will this matrix have?), and L (how many elements will be on this row?)

    System.out.println(Arrays.deepToString(
        transform(new int[] {1,2,3,4,5,6}, 4)
    )); // prints "[[1, 2, 3, 4], [5, 6]]"
Share:
29,419
Admin
Author by

Admin

Updated on August 16, 2020

Comments

  • Admin
    Admin almost 4 years

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

    a is the number of elements in each row. how am i supposed to get [[1, 2, 3], [4]] if my input is int[] array = {1,2,3,4} and int n =3? I'm getting [[4, 5, 6], [7, 8, 9]]?