You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
1.6 KiB
Go
107 lines
1.6 KiB
Go
package utils
|
|
|
|
import (
|
|
"bufio"
|
|
"log"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func ReadLines(fileName string) []string {
|
|
result := []string{}
|
|
file, err := os.Open(fileName)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
result = append(result, scanner.Text())
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
func ParseIntArray(s string, sep string) []int {
|
|
result := []int{}
|
|
|
|
var vals []string
|
|
if sep == " " {
|
|
vals = strings.Fields(strings.TrimSpace(s))
|
|
} else {
|
|
vals = strings.Split(strings.TrimSpace(s), sep)
|
|
}
|
|
|
|
for _, val := range vals {
|
|
n, _ := strconv.Atoi(val)
|
|
result = append(result, n)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
func ParseInt64Array(s string, sep string) []int64 {
|
|
result := []int64{}
|
|
|
|
var vals []string
|
|
if sep == " " {
|
|
vals = strings.Fields(strings.TrimSpace(s))
|
|
} else {
|
|
vals = strings.Split(strings.TrimSpace(s), sep)
|
|
}
|
|
|
|
for _, val := range vals {
|
|
n, _ := strconv.ParseInt(val, 10, 64)
|
|
result = append(result, n)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
func IntPow(x int, y int) int {
|
|
result := 1
|
|
|
|
for i := 0; i < y; i++ {
|
|
result *= x
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
func Int64Pow(x int64, y int64) int64 {
|
|
result := int64(1)
|
|
|
|
for i := int64(0); i < y; i++ {
|
|
result *= x
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// greatest common divisor (GCD) via Euclidean algorithm
|
|
func GCD(a, b int) int {
|
|
for b != 0 {
|
|
t := b
|
|
b = a % b
|
|
a = t
|
|
}
|
|
return a
|
|
}
|
|
|
|
// find Least Common Multiple (LCM) via GCD
|
|
func LCM(a, b int, integers ...int) int {
|
|
result := a * b / GCD(a, b)
|
|
|
|
for i := 0; i < len(integers); i++ {
|
|
result = LCM(result, integers[i])
|
|
}
|
|
|
|
return result
|
|
}
|