Peak Counting

You are given an array of numbers representing the height above the horizon of the mountains from Beautiful British Columbia. Count the number of peaks in the beautiful view and store their number in a variable called numPeaks.

Example

Input:

let numbers = [1, 2, 3, 2, 1, 3, 5, 2, 3, 1]

Expected value:

numPeaks = 3

[collapse]
Hint

Any number with smaller neighbouring numbers counts as a peak.

[collapse]
Solution

let numbers = [1, 2, 3, 2, 1, 3, 5, 2, 3, 1]
var numPeaks = 0
for i in 1..<numbers.count - 1 {
    if numbers[i-1] < numbers[i] && numbers[i] > numbers[i+1] {
        numPeaks += 1
    }
}

[collapse]
1 Star2 Stars3 Stars4 Stars5 Stars (8 votes, average: 3.00 out of 5)
Loading...
Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)