【问题标题】:Sum of to arrays with different array sizes具有不同数组大小的数组的总和
【发布时间】:2023-01-03 00:03:19
【问题描述】:

我正在尝试解决数组问题的总和:

//[1,2,3] + [1,2] should be [1,3,5]

如果数组大小相同,我可以解决这个问题,但是我该如何处理不同的数组大小呢? 这是我现在的代码:

function sumOfArrays(a, b) {

    let result = new Array(Math.max(a.length, b.length)); 
    let carry = 0;

    for (let i = result.length - 1; i >= 0; i--) {
        const elementA = a[i];
        const elementB = b[i];
        const additionResult = elementA + elementB + carry;
        result[i] = (additionResult % 10);
        carry = Math.floor(additionResult / 10);
    }
}

我基本上是将空值放入结果数组如果数组的大小不同

【问题讨论】:

  • const 元素A = a[i] || 0
  • 但是要使它起作用,您需要 i 从 1 到 n 并从相应的数组长度中减去它。否则你向右而不是向左填充。

标签: javascript arrays


【解决方案1】:

如果 2 个数组的长度相同,则可以添加比较。

如果不是,您可以从头开始用 0 填充它,直到它们的长度相同。

然后您的代码将按预期工作(添加return result ;))

const pad = (arr, size, fill = 0) => [ ...Array(size - arr.length).fill(0), ...arr ];

let a = [1,2,3];
let b = [1,2];

if (a.length < b.length) {
    a = pad(a, b.length);
} else if (b.length < a.length) {
    b = pad(b, a.length);
}

function sumOfArrays(a, b) {

    let result = new Array(Math.max(a.length, b.length)); 
    let carry = 0;

    for (let i = result.length - 1; i >= 0; i--) {
        const elementA = a[i];
        const elementB = b[i];
        const additionResult = elementA + elementB + carry;
        result[i] = (additionResult % 10);
        carry = Math.floor(additionResult / 10);
    }
    
    return result;
}

const res = sumOfArrays(a, b);
console.log(res)

但是,由于数组现在的长度相同,我们可以通过使用 map() 并将 (+) 添加到该索引上另一个数组的当前值来简化代码:

const pad = (arr, size, fill = 0) => [ ...Array(size - arr.length).fill(0), ...arr ];

let a = [1,2,3];
let b = [1,2];

if (a.length < b.length) {
    a = pad(a, b.length);
} else if (b.length < a.length) {
    b = pad(b, a.length);
}

function sumOfArrays(a, b) {
    return a.map((n, i) => n + b[i]);
}

const res = sumOfArrays(a, b);
console.log(res)
//  [
//    1,
//    3,
//    5
//  ]

【讨论】:

    【解决方案2】:

    您可以为要添加的索引取一个偏移量。

    function add(a, b) {
        const
            length = Math.max(a.length, b.length),
            offsetA = a.length - length,
            offsetB = b.length - length;
    
        return Array.from(
            { length },
            (_, i) => (a[i + offsetA] || 0) + (b[i + offsetB] || 0)
        );
    }
    
    console.log(...add([1, 2, 3], [1, 2])); // [1, 3, 5]
    console.log(...add([1, 2, 3], [4, 5, 6])); 
    console.log(...add([1, 2, 3, 4], [1])); // [1, 2, 3, 5]
    console.log(...add([1], [1, 2, 3, 4])); // [1, 2, 3, 5]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多