Question

I have difficulties with transcripting the following two functions written in mathematical notation into Java code (the input of both functions is an array with D elements):

enter image description here

Can somebody take a look at the code below and tell me if something is wrong with it?

public double firstFunction(double[] arrayOfElements) {

double sum = 0;
double sumTwo = 0;

for(int i = 0; i < arrayOfElements.length; i++) {
    for(int j = 0; j < i; j++){
        sumTwo = sumTwo + arrayOfElements[j];
    }
    sum = sum + Math.pow(sumTwo, 2);
    }
    return sum;
}

public double secondFunction(double[] arrayOfElements) {
    double maximum = Math.abs(arrayOfElements[0]);
    for (int i = 0; i < arrayOfElements.length; i++) {
        if (Math.abs(arrayOfElements[i]) > maximum) {
            maximum = Math.abs(arrayOfElements[i]); 
        }
    }
    return maximum;
}
Was it helpful?

Solution

The first method should reset sumTwo to zero in every iteration. Currently it accumulates values from one execution of the outer loop to the next. Otherwise it's OK.

Alternatively, and more efficiently, you could notice that the difference between the sumTwo of one iteration and the next is the new array element. This means you don't need the inner loop.

for(int i = 0; i < arrayOfElements.length; i++) {
    sumTwo = sumTwo + arrayOfElements[j];
    sum = sum + Math.pow(sumTwo, 2);
}

The second method is supposed to return the index of the element with maximum absolute value, not the element itself. Note the subindex i in max.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top