Creating a 2d matrix from an array (java)

I have to write a method that creates a 2d matrix from an array, for example: ({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 should I get [[1, 2, 3], [4]] if my input is int [] array = {1,2,3,4} and int n = 3? Am I getting [[4, 5, 6], [7, 8, 9]]?

+3
source share
3 answers

, . -, ; , , value++ (, C *ptr++ ). .

, , . . , , . - i , (row col) . array[i] matrix[row][col].

, . matrix = new int [...][a] [[1, 2, 3], [4, 0, 0]] . , β€” matrix = new int [...][] β€” , , .

+3

, - :

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

MxN, . Arrays.copyOfRange , , M ( ?) L ( ?)

    System.out.println(Arrays.deepToString(
        transform(new int[] {1,2,3,4,5,6}, 4)
    )); // prints "[[1, 2, 3, 4], [5, 6]]"
+1

, , :

public static int[][] toM2(int[] array, int a) {
    int[][] matrix = new int [(array.length + a- 1)/ a][a];
    for (int i = 0; i < array.length; i++) matrix[i/a][i%a] = array[i];
    return matrix;
}

The line int value = array[i]that follows value++indicates that you think of this problem as a C programmer array[i]does not give you a pointer to a value, it just gives you a value.

So, the key is to take the index and convert it into a row and column link:

int row = i/a;
int col = i%a;

There is still a problem where all lines are the same length. With java you do not need to select all lines at once. In fact, you can create a new array for each row. The following is complicated, but it works:

public static int[][] toM3(int[] array, int a) {
    int[][] matrix = new int[(array.length + a - 1) / a][];
    int rowStart = 0;
    for (int i = 0; i < array.length; i++) {
        int row = i/a;
        if (matrix[ row ] == null) {
            matrix[ row ] = new int[ Math.min( a, array.length-rowStart) ];
            rowStart += a;
        }
        matrix[ row ][i % a] = array[i];
    }
    return matrix;
}
0
source

Source: https://habr.com/ru/post/1742622/


All Articles