aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: dd83503d53d4166efe9c54cb46c25fda7649cb61 (plain)
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
package main

import (
	"crypto/rand"
	"fmt"
	"math/big"
	"os"
	"strconv"
	"strings"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Printf("usage: %s <die[+die...]>\n", os.Args[0])
		os.Exit(1)
	}
	dice := strings.Split(os.Args[1], "+")
	var sum int64
	for _, die := range dice {
		if result, err := resolve(die); err != nil {
			fmt.Printf("%v\n", err)
			os.Exit(1)
		} else {
			sum += result
		}
	}
	fmt.Printf("%d\n", sum)
}

func resolve(die string) (int64, error) {
	// try parsing as a die e.g. 2d6
	var (
		num   int
		sides int64
	)
	if fields, err := fmt.Sscanf(die, "%dd%d", &num, &sides); err == nil && fields == 2 {
		var sum int64
		for i := 0; i < num; i++ {
			if r, err := roll(sides); err != nil {
				return 0, err
			} else {
				sum += r
			}
		}
		return sum, nil
	}

	// try just parsing as a number, e.g. +5
	if x, err := strconv.Atoi(die); err != nil {
		return 0, fmt.Errorf("unrecognized die: %s", die)
	} else {
		return int64(x), nil
	}
}

func roll(sides int64) (int64, error) {
	r, err := rand.Int(rand.Reader, big.NewInt(sides))
	if err != nil {
		return 0, err
	}
	return 1 + r.Int64(), nil
}