Refactor some of our tool code.
This commit is contained in:
71
2020/lib/util/file.go
Normal file
71
2020/lib/util/file.go
Normal file
@ -0,0 +1,71 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func InputParserInts(filename string) []int {
|
||||
file, err := os.Open(filename)
|
||||
defer file.Close()
|
||||
|
||||
if err != nil {
|
||||
log.Panicf(err.Error())
|
||||
}
|
||||
|
||||
values := make([]int, 0)
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
x, err := strconv.Atoi(scanner.Text())
|
||||
if err != nil {
|
||||
log.Panicf(err.Error())
|
||||
}
|
||||
values = append(values, x)
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
func InputParserIntMap(filename string) map[int]bool {
|
||||
file, err := os.Open(filename)
|
||||
defer file.Close()
|
||||
|
||||
if err != nil {
|
||||
log.Panicf(err.Error())
|
||||
}
|
||||
|
||||
values := make(map[int]bool)
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
x, err := strconv.Atoi(scanner.Text())
|
||||
if err != nil {
|
||||
log.Panicf(err.Error())
|
||||
}
|
||||
values[x] = true
|
||||
}
|
||||
|
||||
return values
|
||||
}
|
||||
|
||||
func InputParserStrings(filename string) []string {
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
log.Panicf(err.Error())
|
||||
}
|
||||
output := strings.Split(string(data), "\n")
|
||||
return output[:len(output)-1]
|
||||
}
|
||||
|
||||
func InputParserBytes(filename string) [][]byte {
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
log.Panicf(err.Error())
|
||||
}
|
||||
output := bytes.Split(data, []byte("\n"))
|
||||
return output[:len(output)-1]
|
||||
}
|
Reference in New Issue
Block a user