Home >Backend Development >Golang >How Can I Optimize Input Scanning in Go to Avoid Timeouts?

How Can I Optimize Input Scanning in Go to Avoid Timeouts?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 17:04:10375browse

How Can I Optimize Input Scanning in Go to Avoid Timeouts?

Optimizing Input Scanning for Faster Execution

To address the timeout issue experienced with a SPOJ question, specific optimizations are necessary for faster input scanning.

Utilizing bufio.Scanner for Line Reading

Rather than using fmt.Scan alone, leverage bufio.Scanner to efficiently read lines from the input.

Customizing Number Conversion for Speed

Since only numerical input is expected, a custom number converter can be implemented to extract integers directly from raw bytes. This improves performance significantly over using Scanner.Text due to avoiding unnecessary string conversion and overhead.

Custom Number Converter Implementation

The function toInt is designed to convert raw bytes into integers efficiently:

func toInt(buf []byte) (n int) {
    for _, v := range buf {
        n = n*10 + int(v-'0')
    }
    return
}

This function leverages the one-to-one mapping of digits to UTF-8 encoded bytes in the input.

Refined Solution

Combining these optimizations, the improved solution reads as follows:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    var n, k, c int
    scanner := bufio.NewScanner(os.Stdin)

    scanner.Scan()
    fmt.Sscanf(scanner.Text(), "%d %d", &n, &k)

    for ;n > 0; n-- {
        scanner.Scan()
        if toInt(scanner.Bytes())%k == 0 {
            c++
        }
    }

    fmt.Println(c)
}

Benefits of Optimization

This optimized solution significantly improves input scanning speed, ensuring that the program can process the necessary inputs within the allotted time limit. The custom number converter, along with the use of bufio.Scanner, minimizes runtime overhead and enhances program efficiency.

The above is the detailed content of How Can I Optimize Input Scanning in Go to Avoid Timeouts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn