简体   繁体   中英

How do I compare a parameter to elements in an array that are next to it?

I am doing a worksheet for my AP Computer science class and I have run into this question.

"Write the complete definition for the isABeat method. The method accepts an integer parameter and returns whether or not it's a beat: a beat is defined as a value that is greater than its immediate neighbors. You can assume the first and last values do not represent beats."

With this example of an array:

[4, 5, 7, 10, 9, 5, 0, -2, -8, -10, -10, -7]
  • isABeat(3) returns true,
  • isABeat(9) returns false.

Here s the starting code my teacher gave me for the worksheet:

public class EKG { 
    private int[] beats = new int[6000]; // holds data for each bet every tenth of a second for ten minutes
    //constructors, accessors, mutators and toString present but not shown
    public void correctBeatData() {}
    public boolean isABeat(int spot) {}
    public in countBeats() {}
    public int averageBPM() {}
    public int findNextBeat(int where) {}
    public boolean hasArrhythmia() {}

I suppose, having given method: countBeats and field: beats it is enought to write:

public boolean isABeat(int spot) {
    if(spot < 0 || spot >= beats.length) {
        throw new IllegalArgumentException("Argument 'spot' is out of bounds.");
    }

    if(spot == 0 || spot == beats.length - 1) {
        return false;
    }

    return beats[spot] > beats[spot-1] && beats[spot] > beats[spot+1];
}

Here is your solution with documentation:

public boolean isABeat(int spot) //index would have been a better name just saying.
{
       //used this to avoid ArrayOutOfBounds Further down as it will just break when it returns false
      if(spot>=beats.length-1||spot<=0) // spot is out of bounds therefore it is false
       {
           return false;
       }
       //Makes sure it is greater than both neighbors.
       if(beats[spot]>beats[spot-1] && beats[spot] >beats[spot+1])
       return true;
       else 
       return false; //if its false

}

LOGIC:

It tests if spot is out of bounds.. If it is, that means it definitely cannot be a beat. Thus, we break the call by returning false(Avoiding out of bounds in the conditional below that). Next, we check if its neighbors are both less than the value at the spot. If the conditional is satisfied, it will return true. Otherwise, it will return false. Hopefully the addition of the logic and the code help you understand how to go about with the solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM