-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilities.go
138 lines (112 loc) · 2.44 KB
/
utilities.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package runequest
import (
"bufio"
"encoding/csv"
"fmt"
"math/rand"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
)
// Max returns the larger of two ints
func Max(x, y int) int {
if x > y {
return x
}
return y
}
// RollDie rolls and sum dice
func RollDie(max, min, numDice int) int {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
result := 0
for i := 1; i < numDice+1; i++ {
roll := r1.Intn(max+1-min) + min
result += roll
}
return result
}
// TrimSliceBrackets trims the brackets from a slice and return ints as a string
func TrimSliceBrackets(s []int) string {
rs := fmt.Sprintf("%d", s)
rs = strings.Trim(rs, "[]")
return rs
}
// UserQuery creates and question and returns the User's input as a string
func UserQuery(q string) string {
question := bufio.NewReader(os.Stdin)
fmt.Print(q)
r, _ := question.ReadString('\n')
input := strings.Trim(r, " \n")
return input
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
// ToSnakeCase transforms a string to snake case
func ToSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
// ChooseRandom chooses a random element in a slice
// when given l as len(slice)
func ChooseRandom(l int) int {
s := rand.NewSource(time.Now().Unix())
r := rand.New(s)
return r.Intn(l)
}
func readCSVFromURL(url string) ([][]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
reader := csv.NewReader(resp.Body)
data, err := reader.ReadAll()
if err != nil {
return nil, err
}
return data, nil
}
func formatIntArray(a []int) string {
text := strconv.Itoa(a[0])
end := len(a)
if len(a) > 1 {
for i, t := range a {
if i+1 == end {
str := strconv.Itoa(t)
text += "-" + str
}
}
}
return text
}
// IsInIntArray finds an int in an array of ints
func IsInIntArray(a []int, t int) bool {
for _, i := range a {
if t == i {
return true
}
}
return false
}
// NumToArray takes and int and returns an array of [1:int]
func NumToArray(m int) []int {
a := []int{}
for i := 1; i < m+1; i++ {
a = append(a, i)
}
return a
}
// printIntArray prints all intgers in an array
func printIntArray(a []int) string {
text := ""
for _, t := range a {
str := strconv.Itoa(t)
text += str + " "
}
return text
}