从阵列中创建一个二维矩阵(JAVA)阵列、矩阵、创建一个、JAVA

2023-09-07 14:29:01 作者:未来的你身下的她

我应该写一个方法,从一个阵列产生一个二维矩阵,例如:({1,2,3,4},3)应返回矩阵{{1,2,3},{ 4}}

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

一个是在每行中的元素数。我怎么得到[1,2,3] [4]如果我输入的数据类型为int []数组= {1,2,3,4}和INT N = 3?我发现了[[4,5,6],[7,8,9]]

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]]?

推荐答案

您code是有点太离谱基地很容易修复。对于初学者来说,一个三层的嵌套循环是完全没有必要的;同样,你不写值+ (也许你感到困惑,使用的C约定* PTR ++ 走一个数组)。从基本原理上重新开始。

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.

我假设这是家庭作业,所以我不打算只写它。但这里的基本轮廓。结果元素的数量取决于输入数组,而不是输出矩阵的尺寸,所以你的算法应该循环输入元素。对于每一个元素,它的指数的一些基本的数学,,会告诉你,它属于( COL )的输出矩阵。指定数组[我] 矩阵[行] [COL]

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].

有关加分,注意,最后一行通常比其他行短。分配矩阵=新INT [...] [A] 将产生 [1,2,3],[4,0,0] ] ,而不是规定的要求。通过分配阵列&mdash只是外部阵列解决这个问题; 矩阵=新INT [...] [] &mdash;和单独地分配每个子阵列,使得最后一排的一个特例使用模算术

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.