-3

Facing an error Panic Runtime Error index out of range [3] with length 3. The below error seems to indicate the index is out of range or length

panic: runtime error: index out of range [3] with length 3
main.romanToInt(0xc000022080, 0x3, 0x8)
solution.go, line 15
main.__helper__(...)
solution.go, line 30
main.main()
solution.go, line 58
func romanToInt(s string) int {
    romanNum := map[byte]int{
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }

    var sum int = 0
    for i := 0; i <= len(s); i++ {
        currentInt := romanNum[s[i]]
        nextInt := romanNum[s[i+1]]
        if currentInt < nextInt {
            sum = sum + (nextInt - currentInt)
            i += 1
        } else {
            sum = sum + currentInt
        }
    }
    return sum
}

Error pointing to

nextInt := romanNum[s[i+1]]
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
xZile
  • 11
  • 1
  • 8

2 Answers2

3

For i=len(s)-1, the expression s[i+1] accesses the index s[len(s)], which is invalid. The index you are accessing does not exist. Even if you fix it, your loop range includes len(s), so next time around s[i] will be out of range.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
2

Let's say that you pass the string XII to your function. That makes len(s) 3, which means that the body of your loop would (if the panic didn't occur) execute 4 times (when i is 0, 1, 2 and 3 since your condition is i <= len(s).

On the iteration where i is 2 (i.e. it refers to the second I in XII, the last character), when the line

nextInt := romanNum[s[i+1]]

attempts to access the next character (i+1 will be 3) then it will be out of bounds. Remember, slices/arrays are 0 indexed. This is the reason for the panic.

It's also worth nothing that if the panic did not occur when i was 2, then it would certainly occur during the next iteration where i is 3, since 3 is out of bounds for s, on the following line:

currentInt := romanNum[s[i]]

To fix the issue, you need to reconsider how you approach the condition of the loop. Using <= here is likely to cause you a problem. Also, within the body of the loop, you need to consider that when you're looking at the last character in the string, there is not a next character, but your code just assumes that there is. Addressing both of these problems should help you overcome the issue.

Jonathon
  • 15,873
  • 11
  • 73
  • 92