1

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;
}
TheAptKid
  • 1,559
  • 3
  • 25
  • 47
  • 1
    What debugging have you done so far? What is an example of an input case that gives you an incorrect result? – Oliver Charlesworth May 31 '13 at 16:21
  • 1
    I haven't done any debugging since I don't know what kind of result to expect. I'm just asking if the transcription is in order, since I'm not very familiar with the mathematical notation. Also, I don't have any results that could be mapped to a specific input case. – TheAptKid May 31 '13 at 16:23
  • 1
    I'm afraid this isn't a very good fit for Stack Overflow then... If you don't have any way of testing this code, then I'm not sure there's much we can help you with, other than spotting errors by inspection. – Oliver Charlesworth May 31 '13 at 16:24
  • Those voting to close because they don't think the question is approachable should have paid attention to the fact that someone found it approachable enough to answer! – Chris Stratton May 31 '13 at 17:47

1 Answers1

1

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.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thank you for your clarification. One more thing. So the seconds function should return the index of the element, which is the biggest, according to the absolute value. If a had an array [-1,3,-4] the method should return 2? – TheAptKid May 31 '13 at 16:41