According to the task description, the output should be a new array with all elements of array days that are larger than their previous and next elements (in increments of 1). For example, we have as input
[ ]int{3, 2, 4, 3, 7, 9}
and the output should be:
[ ]int{3, 4, 9}
At first I tried to write the next condition:
if days[i] > days[i-1] && days[i] > days[i 1] {
arr = append(arr, days[i])
}
but an error occured: index out of range [-1]
Then I changed the condition and added a special condition for the last element:
package main
import (
"fmt"
)
func chaos(days []int) []int {
var arr []int
for i := 0; i < len(days)-1; i {
if days[i] > days[i 1] {
arr = append(arr, days[i])
}
if days[len(days)-1] > days[len(days)-2] {
arr = append(arr, days[len(days)-1])
}
}
return arr
}
func main() {
fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))
}
But the output is [3 9 9 4 9 9 9]
How to correctly specify the condition for the last element and why the result in my case is incorrect?
CodePudding user response:
The reason 9
is populated multiple times is because you're using below if
condition inside for
loop. Put this if
outside of your for
loop, then you will get the desired output:
if days[len(days)-1] > days[len(days)-2] {
arr = append(arr, days[len(days)-1])
}
However, apart from this also you're comparing i'th
element with the next element only. As per the question, you should also compare it with previous element as well. Below are the possible changes which could be made in your code to work properly:
package main
import (
"fmt"
)
func chaos(days []int) []int {
var arr []int
fmt.Println(len(days))
if days[0] > days[1] {
arr = append(arr, days[0])
}
for i := 1; i < len(days)-1; i {
if (days[i] > days[i 1]) && (days[i] > days[i-1]) {
arr = append(arr, days[i])
}
}
if days[len(days)-1] > days[len(days)-2] {
arr = append(arr, days[len(days)-1])
}
return arr
}
func main() {
fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))
}
https://go.dev/play/p/ndJVc35TM1O
CodePudding user response:
You can add math.MinInt64
(can be considered as negative infinity) to the start and end for the slice to handle the two edge cases easily. Then iterate starting from index 1
to index n-2
(by excluding 0
and n-1
which are the entries we added).
I would try like below.
package main
import (
"fmt"
"math"
)
func chaos(days []int) []int {
var arr []int
// Add negative infinity to the start
days = append([]int{math.MinInt64}, days...)
// Add negative infinity to the end
days = append(days, math.MinInt64)
for i := 1; i <= len(days)-2; i {
if (days[i] > days[i 1]) && (days[i] > days[i-1]) {
arr = append(arr, days[i])
}
}
return arr
}
func main() {
fmt.Println(chaos([]int{3, 2, 4, 3, 7, 9}))
}