从数组创建二维矩阵(java)

发布于 2024-08-30 21:17:11 字数 645 浏览 3 评论 0原文

我应该编写一个从数组创建二维矩阵的方法,例如: ({1, 2, 3, 4}, 3) 应该返回矩阵 {{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 是每行中的元素数量。如果我的输入是 int[] array = {1,2,3,4} 且 int n =3,我应该如何获得 [[1, 2, 3], [4]] ?我得到 [[4, 5, 6], [7, 8, 9]]?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无人问我粥可暖 2024-09-06 21:17:11

您的代码有点偏离基础,无法轻松修复。对于初学者来说,三层嵌套循环是完全没有必要的;另外,您不会通过编写 value++ 来获取数组元素(也许您对使用 *ptr++ 遍历数组的 C 约定感到困惑)。从首要原则重新开始。

我假设这是家庭作业,所以我不会只为你写它。但这是基本轮廓。结果元素的数量取决于输入数组而不是输出矩阵的维度,因此您的算法应该循环输入元素。对于每个元素,其索引 i 的一些基本数学运算将告诉您它在输出矩阵中的位置(rowcol)。将array[i]分配给matrix[row][col]

为了获得奖励积分,请注意最后一行通常比其他行短。分配 matrix = new int [...][a] 将产生 [[1, 2, 3], [4, 0, 0]] 而不是指定的要求。通过仅分配外部数组数组(matrix = new int [...][])并单独分配每个子数组(使用模算术创建最后一行的特殊情况)来解决此问题。

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.

后来的我们 2024-09-06 21:17:11

我认为这样的东西更具可读性:

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

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]]"
凉薄对峙 2024-09-06 21:17:11

我认为以下内容更接近您的想法:

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

int value = array[i] 行后跟 value++ 表明您正在像 C 语言一样思考这个问题程序员。 array[i] 不会给你一个指向值的指针,它只是给你一个值。

因此,关键是获取索引并将其转换为行和列引用:

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

仍然存在行长度相同的问题。使用java,您不必同时分配所有行。事实上,您可以为每一行创建一个新数组。下面的方法很复杂,但是有效:

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

I think the following is closer to what you have in mind:

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] followed by value++ indicate that you are thinking about this problem like a C programmer. The 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 transform it into row and column references:

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

There is still the problem of the rows all being the same length. With java you don't have to allocate all the rows at the same time. In fact, you can 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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文