从数组创建二维矩阵 (java) [英] Creating a 2d matrix from an array (java)

查看:31
本文介绍了从数组创建二维矩阵 (java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该编写一个从数组创建二维矩阵的方法,例如: ({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;
  }
}

a 是每行中的元素数.如果我的输入是 int[] array = {1,2,3,4} 和 int n =3,我应该如何得到 [[1, 2, 3], [4]] ?我得到 [[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]]?

推荐答案

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

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,将告诉您它在输出矩阵中的位置(rowcol).将 array[i] 赋值给 matrix[row][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].

对于奖励积分,请注意最后一行通常比其他行短.分配 matrix = new int [...][a] 将产生 [[1, 2, 3], [4, 0, 0]] 而不是规定的要求.通过仅分配数组的外部数组来解决此问题 —matrix = new int [...][] —并单独分配每个子数组,使用模数算法对最后一行进行特殊处理.

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.

这篇关于从数组创建二维矩阵 (java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆