-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroll.go
106 lines (91 loc) · 2.19 KB
/
roll.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
package main
import (
"crypto/rand"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"github.com/Knetic/govaluate"
)
func main() {
input := strings.Join(os.Args[1:], " ")
output := rollDice(input)
result, err := evaluate(output)
if err != nil {
panic(err)
}
fmt.Printf("%s => %d\n", input, result)
}
var (
rawRegex = `(\d*)d(\d*)`
re = regexp.MustCompile(rawRegex)
)
func rollDice(input string) string {
matches := re.FindAllStringSubmatchIndex(input, -1)
for i := len(matches) - 1; i >= 0; i-- {
match := matches[i]
rawNumDice := input[match[2]:match[3]]
numDice := 1
if rawNumDice != "" {
var err error
numDice, err = strconv.Atoi(rawNumDice)
if err != nil {
panic(fmt.Errorf("failed to parse number of dice: %q", rawNumDice))
}
}
rawSides := input[match[4]:match[5]]
sides, err := strconv.Atoi(rawSides)
if err != nil {
panic(fmt.Errorf("failed to parse dice sides: %q", rawSides))
}
rolls, err := rollDie(sides, numDice)
joinedRolls := joinRolls("+", rolls)
input = input[:match[0]] + joinedRolls + input[match[1]:]
}
return input
}
func rollDie(sides int, count int) ([]int, error) {
if sides <= 0 {
return nil, fmt.Errorf("sides must be >= 1")
}
if sides > 256 {
return nil, fmt.Errorf("sides cannot be > 256")
}
if count <= 0 {
return nil, fmt.Errorf("count must be >= 1")
}
rolls := make([]byte, count)
_, err := rand.Read(rolls)
if err != nil {
return nil, fmt.Errorf("unable to get random value: %w", err)
}
result := []int{}
for _, roll := range rolls {
result = append(result, int(roll)%sides+1)
}
return result, nil
}
func joinRolls(sep string, rolls []int) string {
str := &strings.Builder{}
str.WriteString("(")
for i := 0; i < len(rolls); i++ {
str.WriteString(strconv.Itoa(rolls[i]))
if i < len(rolls)-1 {
str.WriteString(sep)
}
}
str.WriteString(")")
return str.String()
}
func evaluate(input string) (int, error) {
expr, err := govaluate.NewEvaluableExpression(input)
if err != nil {
return 0, fmt.Errorf("failed to parse expression: %w", err)
}
result, err := expr.Evaluate(nil)
if err != nil {
return 0, fmt.Errorf("failed to evaluate expression: %w", err)
}
return int(result.(float64)), nil
}