javascript 数组大小不同的数组的和

7fyelxc5  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(136)

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

//[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);
    }
}

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

afdcj2ne

afdcj2ne1#

如果两个数组长度相同,则可以添加比较。
如果不是,你可以从一开始就用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
//  ]
7qhs6swi

7qhs6swi2#

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

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]

相关问题