import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func validatoreSequenza(sequenza []int) {
for posizione := 0; posizione <= len(sequenza); posizione++ {
if posizione == 0 {
continue
} else if posizione%2 == 0 { // pari
if sequenza[posizione] < sequenza[posizione-1] {
fmt.Printf("Valore in posizione %v non valido.", posizione)
return
}
} else if posizione%2 == 1 { // dispari
if sequenza[posizione] > sequenza[posizione-1] {
fmt.Printf("Valore in posizione %v non valido.", posizione)
return
}
} else {
fmt.Println("Sequenza valida.")
return
}
}
}```
In this code it is giving me the "out of range" error at line 30 and 55. I've been thinking for a while about what I did wrong but still couldn't figure out, please help me out
#index out of range
23 messages · Page 1 of 1 (latest)
- instead of starting
posizioneat 0, why not just start withif posizione := 1; ...? - use a switch statement here
- you say you get an out of range error at line 30 and 55, but i don't think there are 30 lines in the snippet you've shared 🤔
which line of code specifically has the error?
if sequenza[posizione] > sequenza[posizione-1] {
this one @slender prairie and
validatoreSequenza(intSlice)
this other one
well, your for loop condition is posizione <= len(sequenza)
what happens when posizion == len(sequenza)?
so I should put it posizione < len(sequenza)
sure
for my particular case I need posizione to start from 0
well, from your implementation, that doesn't seem to be the case
because you just skip that
I skip it cause the first element cannot be compared with his previous one
ok, so start posizione at 1 so you dont check the first element..?
(well.. you would, just that it would be the -1 part, instead of the first element)
I use the index as positioning in the array, so if we are in a odd or even position I know how to react ( based on the logic of the code I need to write )
i dont see how thats relevant to the first value of i..?
if I have 5 4 9 2 6 and I index them starting from 0 I would have that 5 is at position 0, 4 position 1, 9 position 2 and so on
as you can see in the software
I make some if statements based on if the position is odd or even
if I would put 1 as starting value of position then I would get different outputs
or at least this is what I understand