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

How Can We Optimize Input Scanning in Go to Avoid Timeouts in Competitive Programming?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 21:56:15701browse

How Can We Optimize Input Scanning in Go to Avoid Timeouts in Competitive Programming?

Faster Input Scanning for Enhanced Code Performance

The provided program aims to solve a coding challenge from SPOJ. However, the input scanning process appears to be causing a timeout issue. Despite utilizing bufio for faster input reading, the code still encounters this problem.

To address this, let's explore two optimization techniques:

1. Utilizing bufio.Scanner

Instead of employing fmt.Fscan for line-by-line input reading, we can utilize bufio.Scanner. This approach streamlines the process by leveraging the Bytes() method, which returns raw bytes directly rather than converting them to strings.

2. Custom Integer Conversion Function

To further enhance speed, we can introduce a specialized converter function, toInt(), which efficiently extracts integers from the raw bytes obtained from bufio.Scanner. This function directly translates the byte sequence representing a decimal number into an integer, eliminating the overhead of string conversion.

The updated code incorporating these optimizations is 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)
}

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

By combining bufio.Scanner with the custom toInt() function, we significantly increase the efficiency of input reading and conversion. Consequently, this optimized solution is expected to perform much faster than the original version, resolving the timeout issue encountered earlier.

The above is the detailed content of How Can We Optimize Input Scanning in Go to Avoid Timeouts in Competitive Programming?. 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