Home  >  Article  >  Backend Development  >  How to Read Integers from Space-Separated Input in Golang: A Recursive Approach?

How to Read Integers from Space-Separated Input in Golang: A Recursive Approach?

DDD
DDDOriginal
2024-10-30 21:01:30127browse

How to Read Integers from Space-Separated Input in Golang: A Recursive Approach?

Read Integers from Space-Separated Input in Golang: An Efficient Approach

In programming, reading a set of integers separated by space from the standard input and storing them in an array efficiently is a common task. One way to achieve this is using a straightforward for loop. However, there exists a technique that leverages recursion to minimize the code while maintaining optimal performance.

Using Recursion Without Explicit Loops

The following Go code snippet demonstrates how to read integers from standard input without using for or goto loops:

<code class="go">package main

import "fmt"

func main() {
    var n int
    fmt.Println(`Enter the number of integers`)
    if _, err := fmt.Scan(&n); err != nil {
        panic(err)
    }
    fmt.Println(`Enter the integers`)
    all := make([]int, n)
    ReadN(all, 0, n)
    fmt.Println(all)
}

// Recursively reads n integers into all starting from position i.
func ReadN(all []int, i, n int) {
    if n == 0 {
        return
    }
    if _, err := fmt.Scan(&all[i]); err != nil {
        panic(err)
    }
    ReadN(all, i+1, n-1)
}</code>

Example Output

Suppose the standard input contains the integers:

Enter the number of integers
3
Enter the integers
23 45 66

Running the program would output:

[23 45 66]

Optimizing Input Scanning

To further optimize input scanning, consider replacing the fmt.Scan function in ReadN with a custom reader that enables faster input processing:

<code class="go">type reader struct {
    val int
}

func (r *reader) Read(b []byte) (int, error) {
    w, err := fmt.Scanf("%d", &r.val)
    if err != nil {
        return w, err
    }
    b[0] = byte(r.val)
    return 1, err
}</code>

In this optimized implementation, a custom reader is created with a field val to hold the integer value. The Read method uses fmt.Scanf to read an integer from the standard input and store it in val. When reading from the custom reader, only one byte is processed, significantly reducing overhead.

By incorporating these techniques, you can efficiently read sets of integers from standard input in Golang, maximizing performance while minimizing code complexity.

The above is the detailed content of How to Read Integers from Space-Separated Input in Golang: A Recursive Approach?. 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