Im trying to build a code that when the user inputs a sequence of numbers it will go through the sequence comparing each numbers and for every new biggest number in the sequence it will sum all the previous ones
func main() {
var numeri []int
numeri = GetInputSlice()
fmt.Println(numeri)
var sum int
num := len(numeri)
for i := 0; i < num - 1 ; i {
sum = numeri[i]
if numeri[i] > numeri[i 1] || numeri[i] == num - 1 {
fmt.Println(sum)
sum = 0
}
}
}
full code over here: https://go.dev/play/p/13ljQPmKaRA
if I input this sequence of numbers [1 2 13 0 7 8 9 -1 0 2] I would like to get 16, 24 and 1. But in my code I only get 16 and 24 without getting the last 1 and I can't figure out a way to fix this.
CodePudding user response:
Only numeri[i]
is ever added to sum
, and your loop never visits the last item (i < num - 1
), so how could the last item be ever added?
Range through the whole slice, perform the addition, but only compare to the next element if you're not at the last one. If we're at the last one, we also want to print, so we may use a single condition
i == max || numeri[i] > numeri[i 1]
Where the comparison to the next element will not be executed if i == max
(short circuit evaluation).
For example:
max := len(numeri) - 1
for i, v := range numeri {
sum = v
if i == max || v > numeri[i 1] {
fmt.Println(sum)
sum = 0
}
}
This will output (try it on the Go Playground):
[1 2 13 0 7 8 9 -1 0 2]
16
24
1