#index out of range

23 messages · Page 1 of 1 (latest)

urban scaffold
#

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
slender prairie
#
  1. instead of starting posizione at 0, why not just start with if posizione := 1; ...?
  2. use a switch statement here
  3. 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?

urban scaffold
#

if sequenza[posizione] > sequenza[posizione-1] {

#

this one @slender prairie and

#

validatoreSequenza(intSlice)

#

this other one

slender prairie
#

well, your for loop condition is posizione <= len(sequenza)

#

what happens when posizion == len(sequenza)?

urban scaffold
slender prairie
#

sure

urban scaffold
slender prairie
#

well, from your implementation, that doesn't seem to be the case

#

because you just skip that

urban scaffold
slender prairie
#

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)

urban scaffold
slender prairie
#

i dont see how thats relevant to the first value of i..?

urban scaffold
#

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