用其他数组填充一个数组,但用0填充其余数组

时间:2018-02-14 19:54:19

标签: java arrays vector

我正在创建一个小型java程序,它可以进行一些矢量数学运算,而且我会遇到加法和减法。

我们必须创建自己的vector类,它包含的所有内容都是一个带有值的Array,所以

Vector a = new Vector(1, 2, 3) //this would make a vector with [1, 2, 3]
Vector b = new Vector(4, 3) //this would make a vector with [4, 3]

我不能用现在的矢量添加a + b,因为如果我遍历Vector a中的每个索引,我会得到一个带有矢量b的界限错误。

如何创建一个新数组,其中包含向量b的所有值,其余为0' s

//a is [1, 2, 3]
//b is [4, 3]
fix = [4, 3, 0]; //same as b but with trailing 0's so a.length == fix.length

3 个答案:

答案 0 :(得分:0)

实现不使用任何库的伪代码"你的教授的要求:

int maxlength = max(a.length, b.length)

Vector c = ... // create Vector of maxlength length

for (int i = 0; i < maxlength; i++)
{
  if (i < a.length)
  {
    c[i] += a[i];
  }
  if (i < b.length)
  {
    c[i] += b[i];
  }
}

答案 1 :(得分:0)

得到Vector a的长度,在你的情况下它是3 得到向量b的长度,在你的情况下它是2

所以0的数字放在Vector b 3-2 = 1

用于从索引2开始的循环,索引2是Vector b的长度。 并循环直到Vector a的长度

for(int i=b.length;i<a.length;i++){
    b[i]=0;
}

答案 2 :(得分:0)

我认为你应该能够在没有帮助的情况下做到这一点。 (而且我确定这是你老师想要的!)

但这里有一些提示。你说:

  

我不能用现在的矢量添加a + b,因为如果我遍历Vector a中的每个索引,我会得到一个带有矢量b的界限错误。

步骤#1: test 表示您将获得边界错误的情况...并且只有在您没有得到边界错误时才进行分配; e.g。

  // pseudo-code ... for illustration purposes only
  int len = /* calculate length in source array */
  for (int i = 0; i < len; i++) {
      int j = /* calculate index in target array */
      if (j < targetArray.length) { // test that j is "in bounds"
           targetArray[j] = ...
      }
  }

步骤2:一旦你弄清楚步骤#1,你应该能够通过将if测试结合到len测试中来提升 {1}}。 Math.max(int, int)功能非常有用。