Sum of Arrays of Different Size

Sum of arrays of different size

You can use something like this:

a.flat_map{|x| x.in_groups_of(a.max_by(&:size).size, 0)}.transpose.map(&:sum)

Or this:

a.max_by(&:size).map.with_index{|_, i| a.sum{|x| x[i]||0}}

How to add two different sized arrays?

You can define a destination array with a length of the max of both source arrays. After that you just do array bounds-checking. Of course, you should also add checks for null before you even begin to loop over c.

import java.util.Arrays;

class AddArrays {
private static int[] a = new int[] { 1, 2, 3 };
private static int[] b = new int[] { 3, 2 };
private static int[] c = add(a, b);

private static int[] add(int[] a, int[] b) {
int[] c = new int[(int) Math.max(a.length, b.length)];
for (int i = 0; i < c.length; i++) {
if (a.length > i) {
c[i] += a[i];
}
if (b.length > i) {
c[i] += b[i];
}
}
return c;
}

public static void main (String[] args) {
System.out.println(Arrays.toString(c));
}
}

Output:

[4, 4, 3]

sum of two arrays of different length

arraya = [1,1,1,1,1,1,1]
arrayb = [0,1,2]

for i in range(len(arraya)):
arraya[i] += arrayb[i % len(arrayb)]

print arraya

Produces
[1, 2, 3, 1, 2, 3, 1]

How do I sum the elements of an arbitrary number of arrays with different lengths in Javascript?

Use a nested array, and loop over the array rather than hard-coding two array variables.

You can use arrays.map() to get all the lengths so you can calculate the maximum length. And arrays.reduce() to sum up an element in each array.

const addTogether = (...arrays) => {
let result = [];
let len = Math.max(...arrays.map(a => a.length));
for (let i = 0; i < len; i++) {
result.push(arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0));
}
return result
}

console.log(addTogether([1, 2, 3], [4, 5], [6]));

How to add values of two arrays that are different sizes in length?

func combine2Arrays(array1:[Int], array2:[Int]) -> [Int] {
var finalArray:[Int] = []
let maxSize = max(array1.count, array2.count)

for i in 0..<maxSize {
let valToAdd1 = (array1.count > i ? array1[i] : 0)
let valToAdd2 = (array2.count > i ? array2[i] : 0)
let finalVal = valToAdd1 + valToAdd2
finalArray.append(finalVal)
}
return finalArray
}

print(combine2Arrays(array1: [1,2,3], array2: [1,2,3,5]))

OR

func combine2Arrays(array1:[Int], array2:[Int]) -> [Int] {
var finalArray:[Int] = zip(array1,array2).map(+)
let largerArray = array1.count > array2.count ? array1 : array2
let smallerArray = array1.count > array2.count ? array2 : array1
let min = smallerArray.count
let max = largerArray.count
for i in min..<max {
finalArray.append(largerArray[i])
}
return finalArray
}

print(combine2Arrays(array1: [1,2,3], array2: [1,2,3,5]))

Java: How to sum the elements of two arrays with different lengths

Actually, you declare an int[] array with the capacity as Math.max(num1.length, num2.length).

It is not encough. You should set the capacity as Math.max(num1.length, num2.length) +1.

Why?

See if num1 is {1,9,9,9} and num2 is {9,9,9,9}, how can the arraySum to represent the sum {1,1,9,9,8}?

So we need to declare it as below to consider if carry is needed.

 int[] arraySum = new int[capacity + 1];

Then when print the sum, check if arraySum[0] is 0 or 1, if it euqals to 0, do not print it in Console.

Modified code for reference is as follows:

package question;

public class Example {

public static void main(String[] args) {

// for the same lengths
int[] num1 = { 1,9,9,9 };
int[] num2 = { 9,9,9,9};// {9,9,9}

// 1999+9999 = 11998, its length is greater than the max
int capacity = Math.max(num1.length, num2.length);
int[] arraySum = new int[capacity + 1];

int len2 = num2.length;
int len1 = num1.length;

if (len1 < len2) {
int lengthDiff = len2 - len1;

/*
* Flag for checking if carry is needed.
*/
boolean needCarry = false;

for (int i = len1 - 1; i >= 0; i--) {
/**
* Start with the biggest index
*/
int sumPerPosition =0;

if (needCarry) {
sumPerPosition = num1[i] + num2[i + lengthDiff] +1;
needCarry = false;
}else
{
sumPerPosition = num1[i] + num2[i + lengthDiff];
}

if (sumPerPosition > 9) {
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
needCarry = true;
}else
{
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
}
}

/**
* Handle the remaining part in nun2 Array
*/

for (int i = lengthDiff - 1; i >= 0; i--) {
/*
* Do not need to care num1 Array Here now
*/

if(needCarry){
arraySum[i + 1] = num2[i]+1;
}else
{
arraySum[i + 1] = num1[i] ;
}

if (arraySum[i + 1] > 9) {
arraySum[i + 1] = arraySum[i + 1] % 10;
needCarry = true;
} else {
needCarry = false;
}

}

/*
* Handle the last number, if carry is needed. set it to 1, else set
* it to 0
*/
if (needCarry) {
arraySum[0] = 1;
} else {
arraySum[0] = 0;
}

} else {
int lengthDiff = len1 - len2;

/*
* Flag for checking if carry is needed.
*/
boolean needCarry = false;

for (int i = len2 - 1; i >= 0; i--) {
/**
* Start with the biggest index
*/
int sumPerPosition = 0;

if (needCarry) {
sumPerPosition = num2[i] + num1[i + lengthDiff] +1;
needCarry = false;
}else
{
sumPerPosition = num2[i] + num1[i + lengthDiff];
}

if (sumPerPosition > 9) {
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
needCarry = true;
}else
{
arraySum[i + lengthDiff + 1] = sumPerPosition % 10;
}
}

/**
* Handle the remaining part in nun2 Array
*/

for (int i = lengthDiff - 1; i >= 0; i--) {
/*
* Do not need to care num1 Array Here now
*/

if(needCarry){
arraySum[i + 1] = num1[i]+1;
}else
{
arraySum[i + 1] = num1[i] ;
}

if (arraySum[i + 1] > 9) {
arraySum[i + 1] = arraySum[i + 1] % 10;
needCarry = true;
} else {
needCarry = false;
}

}

/*
* Handle the last number, if carry is needed. set it to 1, else set
* it to 0
*/
if (needCarry) {
arraySum[0] = 1;
} else {
arraySum[0] = 0;
}
}

/*
* Print sum
*
* if arraySum[0] ==1, print 1
*
* Do not print 0 when arraySum[0] ==0
*/
if(arraySum[0] == 1)
{
System.out.print(1);
}
for (int i = 1; i < arraySum.length; i++) {

System.out.print(arraySum[i]);
}
}
}

An example that num1 is {1,9,9,9} and num2 is {9,9,9,9}, the sum result is as follows:

output in Console:

11998

python, summing numpy arrays of same dimensions, different shapes with offset and rolling over the end

The rolling can be simulated with the simple modulo operator.

Given some indices of where you want to add a and b together, it is essentially just doing a[indices] += b.

a = np.array([1, 1, 1, 1, 1])
b = np.array([5, 6])
offset = 1

indices = np.arange(offset, len(b)+offset) % len(a)
a[indices] += b
# np.add.at(a, indices, b) - if you want to do the operation unbuffered

Output in a:

array([1, 6, 7, 1, 1])
a = np.array([1, 1, 1, 1, 1])
b = np.array([5, 6, 7, 8])
offset = 3

indices = np.arange(offset, len(b)+offset) % len(a)
a[indices] += b

Output in a:

array([8, 9, 1, 6, 7])

You could also use np.bincount for this:

a = np.array([1, 1, 1, 1, 1])
b = np.array([5, 6, 7, 8])
offset = 3

indices = np.arange(offset, len(b)+offset) % len(a)
np.bincount(indices, b)+a

Output:

array([8., 9., 1., 6., 7.])

Unfortunately, it is not possible to specify a result buffer for np.bincount, which would make +a operation obsolete.

EDIT

If you are interested in making it fast I would suggest dividing the in-place add into 2 slices:

a = np.array([1, 1, 1, 1, 1])
b = np.array([5, 6, 7, 8])
offset = 3

size = len(a) - offset
s1 = slice(offset, offset + size)
s2 = slice(None,size)

size = len(b) - size
s3 = slice(None, size)
s4 = slice(size, None)

a[s1] += b[s2]
a[s3] += b[s4]

Output in a:

array([8, 9, 1, 6, 7])


Related Topics



Leave a reply



Submit