John Apple
John Apple

Reputation: 11

How to calculate the alternating sum of two arrays in Java?

I have to write a function "alternatingSum(a)" that takes an array of numbers and returns the alternating sum (where the sign alternates from positive to negative or vice versa).

For example:

int[] a = { 5, 3, 8, 4 };
Assert(alternatingSum(a) == 6); // because 5-3+8-4 == 6

So far I have tried to take the array and check to see if the index is odd (not including i=0) then subtract it from the i+1, and if it is even do the same thing except add the two. Am I on the right track with this?

Here is my code:

class foo {
    public static int alternatingSum(int[] a){
        int sum=0;
        for (int i=0;i<a.length;i++){
            if (i==0){
                sum+=a[0]-a[1];
            }
            if (i%2 == 0){
                sum+=(a[i]+a[i+1]);
            }
            if (i%2 == 1){
                sum+=(a[i]-a[i+1]);
            }
        }
        return sum;
    } 

    public static void testAlternatingSum(){
        System.out.println("testing code");
        int[] a = { 5, 3, 8, 4 };
        assert (alternatingSum(a) == 6); // because 5-3+8-4 == 6
    }

    public static void main(String[] args){
        testAlternatingSum();
    }
}

Upvotes: 1

Views: 2993

Answers (2)

ahmetyavuzoruc
ahmetyavuzoruc

Reputation: 155

Easy to read..

int[] alternatingSums(int[] a) {

    int sum1 = 0;
    int sum2 = 0;

    for(int i =0; i < a.length; i++){
        
        if((i % 2) != 1){
            sum1 += a[i];
        }else{
            sum2 += a[i];
        }
    }

    int[] result = {sum1 , sum2};
    
    return result; 
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201497

a for loop

I would just keep a boolean flag for even (and toggle it with every loop iteration). If it's an even number, than we're performing addition. But if it's not an even number (it's odd) then we can perform an unary negative operation. That might look something like,

int sum = 0;
boolean even = true;
for (int i = 0; i < a.length; i++) {
    sum += even ? a[i] : -a[i];
    even = !even
}
return sum;

for-each loop

and you could also use a for-each loop and write it like

boolean even = true;
int sum = 0;
for (int value : a) {
    sum += even ? value : -value;
    even = !even;
}
return sum;

Upvotes: 3

Related Questions