1

I have edited a java method for finding peaks by comparing its neighboring elements. But I have a problem in storing the values in the output array...

Here is the method that is edited, commented is my problem

public static int[] peakInArray(int[] arr2){
    int i;
    int lenghtInput = arr2.length;
    int[] peaks = new int[lenghtInput];
    for (i = 1; i<arr2.length - 1; i++) {
        if (arr2[i] > arr2[i - 1] && arr2[i] > arr2[i + 1]);
       // PROBLEM: store arr2[i] in peaks
        peaks[i] = arr2[i];
    }
    return peaks;
}
6
  • 1
    What is the problem you are facing actually Commented May 5, 2016 at 17:03
  • Is there a compilation/runtime error? If so, please paste it. Is something else going wrong? Telling us you have a "problem" is really vague. Commented May 5, 2016 at 17:04
  • if the condition is satisfy you want to store that value in another array right still you are using same index i for peaks !! Commented May 5, 2016 at 17:08
  • 8
    The problem is that you've used if(...); the ; at the end makes this if statement useless. Commented May 5, 2016 at 17:08
  • OP, if your issue is that peaks is storing everything from arr2, then what @Titus eluded to (replace ; with {}, like your for loop) is likely the solution. If you notice other problems, please post more detailed info about what the actual problem is. Commented May 5, 2016 at 17:20

2 Answers 2

1

Like everyone already said, your if statement shouldn't be working the way you have it. It needs to be:

if(yourComparison){
   peaks[i] = arr2[i];
}

Also, if you want your result to only be as big as it needs to be, you need to use an ArrayList. There's an example at the bottom of this page:

http://www.tutorialspoint.com/java/java_arraylist_class.htm

Sign up to request clarification or add additional context in comments.

Comments

0

To all who helped me in my problem, thanks! I've figured it out with your help and with some researches.

Here is the final method...

public static int[] peakInArray(int[] arr2){

    int lengthInput = arr2.length;
    int[] peaks = new int[lengthInput];
    int peakIndex = 0;

    for (int i = 1; i<lengthInput - 1; i ++) {
        if (arr2[i] > arr2[i - 1] && arr2[i] > arr2[i + 1]) {
            //Store arr2[i] in peaks
            peaks[peakIndex] = arr2[i];
            peakIndex++;
        }
    }
 return peaks;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.