Skip to content

Instantly share code, notes, and snippets.

@go-ive
Created September 17, 2013 13:43
Show Gist options
  • Save go-ive/6594474 to your computer and use it in GitHub Desktop.
Save go-ive/6594474 to your computer and use it in GitHub Desktop.
Reddit DailyProgrammer Challenge #130 - Roll the Dies
package main
import (
"fmt"
"regexp"
"os"
"log"
"strings"
"strconv"
"math/rand"
"time"
)
func rollDice(min int, max int) int {
return rand.Intn(max) + min
}
func main() {
rand.Seed(time.Now().UnixNano())
value := os.Args[1]
pattern := regexp.MustCompile("^[0-9]+d[0-9]+$")
if !pattern.MatchString(value) {
log.Fatalf("%s does not match the general expected pattern: ###d###", value)
}
dPos := strings.Index(value, "d")
if dPos > 3 {
log.Fatal("Cannot roll that many times...")
}
numPattern := regexp.MustCompile("[0-9]+")
num := numPattern.FindString(value)
mPattern := regexp.MustCompile("d[0-9]+")
m := mPattern.FindString(value)[1:]
numRolls, err := strconv.Atoi(num)
if err != nil {
log.Fatal("Error parsing number of rolls!")
}
numFaces, err := strconv.Atoi(m)
if err != nil {
log.Fatal("Error parsing number of faces!")
}
if numRolls < 1 || numRolls > 100 {
log.Fatal("Number of rolls must be between 1 and 100")
}
if numFaces < 2 || numFaces > 100 {
log.Fatal("Number of faces must be between 2 and 100")
}
for i := 0; i < numRolls; i++ {
fmt.Printf("%d ", rollDice(1, numFaces))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment