Micro-Scope
Micro-Scope

Reputation: 75

Sum of to arrays with different array sizes

I'm trying to solve sum of to array problem:

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

I'm able to solve this if the array are the same size, but how can I deal with different array sizes? Here is my code for now:

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

I'm basically getting null values into the result array If there is a difference in the size of the array

Upvotes: 0

Views: 58

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take an offset for the index to add.

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]

Upvotes: 1

0stone0
0stone0

Reputation: 44035

You could add a comparison if the 2 arrays are the same length.

If not, you can 'pad' it from the beginning with 0's until ther are the same length.

Then your code will work as expected (after adding 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)


However, since the array's are now the same length, we can simplefy the code a lot by using map() and add (+) to current value of the other array on that index:

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

Upvotes: 1

Related Questions