Search code examples
arraysgobuffer

Scan-read trouble when a big number appears Golang


Trying to solve https://codeforces.com/problemset/problem/803/B My code works fine for smaller inputs, but it keeps getting runtime-error when tests with big numbers appear(9-digit numbers). it throws me a panic at the moment I try to check scanned array value for a first time (if street[i] == 0). Since everything is fine for smaller inputs, and then it suddenly mentions panic: runtime error: index out of range [1] with length 1, I suppose that it is some kind of scanning and storing value problem. However, I wasn't able to fix it by myself. How can I bypass this "restrictions"?

Code example:

package main

import (
    "bufio"
    "math"
    "os"
    "strconv"
    "strings"
)

func closestZero(houses int, street []int) []int {
    distance := make([]int, houses)
    if street[0] == 0 {
        distance[0] = 0
    } else {
        distance[0] = math.MaxInt32
    }
    for i := 1; i < houses; i++ {
        distance[i] = distance[i-1] + 1
        if street[i] == 0 {
            distance[i] = 0
        }
    }
    if street[houses-1] == 0 {
        distance[houses-1] = 0
    }
    for i := houses - 2; i >= 0; i-- {
        distance[i] = min(distance[i], distance[i+1]+1)
        if street[i] == 0 {
            distance[i] = 0
        }
    }
    return distance
}
func main() {
    scanner := makeScanner()
    houses := readInt(scanner)
    street := readArray(scanner)
    printArray(closestZero(houses, street))
}

func makeScanner() *bufio.Scanner {
    const maxCapacity = 3 * 1024 * 1024
    buf := make([]byte, maxCapacity)
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Buffer(buf, maxCapacity)
    return scanner
}

func readArray(scanner *bufio.Scanner) []int {
    scanner.Scan()
    listString := strings.Split(scanner.Text(), " ")
    arr := make([]int, len(listString))
    for i := 0; i < len(listString); i++ {
        arr[i], _ = strconv.Atoi(listString[i])
    }
    return arr
}

func readInt(scanner *bufio.Scanner) int {
    scanner.Scan()
    stringInt := scanner.Text()
    res, _ := strconv.Atoi(stringInt)
    return res
}

func printArray(arr []int) {
    writer := bufio.NewWriter(os.Stdout)
    for i := 0; i < len(arr); i++ {
        writer.WriteString(strconv.Itoa(arr[i]))
        writer.WriteString(" ")
    }
    writer.Flush()
} 

Thanks.


Solution

  • Changed ints to int64 and resized buff.