Last active
October 24, 2022 03:43
-
-
Save ntheanh201/cc061da0938d812da832d360d67bcabb to your computer and use it in GitHub Desktop.
Golang fast reader standard input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"os" | |
"regexp" | |
"strconv" | |
"strings" | |
) | |
type FastReader struct { | |
Reader *bufio.Reader | |
Re *regexp.Regexp | |
} | |
func NewReader(useRegex bool) *FastReader { | |
var re *regexp.Regexp | |
if useRegex { | |
re = regexp.MustCompile(`[-]?\d[\d,]*[.]?[\d{2}]*`) | |
} | |
return &FastReader{Reader: bufio.NewReader(os.Stdin), Re: re} | |
} | |
func (f *FastReader) nextInt() int { | |
numberString, _ := f.Reader.ReadString('\n') | |
numberString = strings.TrimSuffix(numberString, "\n") | |
n, _ := strconv.Atoi(numberString) | |
return n | |
} | |
func (f *FastReader) nextIntScan() int { | |
var i int | |
_, err := fmt.Fscan(f.Reader, &i) | |
if err != nil { | |
fmt.Println(err) | |
return 0 | |
} | |
return i | |
} | |
func (f *FastReader) nextLineInt() []int { | |
stringNumbers, _ := f.Reader.ReadString('\n') | |
stringNumbersArray := f.Re.FindAllString(stringNumbers, -1) | |
var res []int | |
for _, i := range stringNumbersArray { | |
j, err := strconv.Atoi(i) | |
if err != nil { | |
panic(err) | |
} | |
res = append(res, j) | |
} | |
return res | |
} | |
func (f *FastReader) nextLine() string { | |
line, _ := f.Reader.ReadString('\n') | |
line = strings.TrimSpace(strings.TrimSuffix(line, "\n")) | |
return line | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment