diff options
author | Luke Shumaker <LukeShu@sbcglobal.net> | 2013-09-07 15:03:57 -0400 |
---|---|---|
committer | Luke Shumaker <LukeShu@sbcglobal.net> | 2013-09-07 15:03:57 -0400 |
commit | 5fe5ef3d949f01ad68a3d683d6d69ffecc364fac (patch) | |
tree | 579a699d6794ad200be01113251cd07c23d6868a | |
parent | 23ebdbace364ffc2e27403e103594c12c0002b5b (diff) |
rewrite roll in Go
-rw-r--r-- | Makefile | 2 | ||||
-rw-r--r-- | roll.go | 52 | ||||
-rw-r--r-- | roll.php | 35 |
3 files changed, 54 insertions, 35 deletions
@@ -43,6 +43,8 @@ clean: %: %.php install -m755 $< $@ +%: %.go + go build $< -o $@ .gitignore: Makefile printf '%s\n' '*~' $(BINFILES) > $@ @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "math/rand" + "os" + "regexp" + "strconv" + "time" +) + +func usage() { + fmt.Printf("Arguments are in the format [<COUNT>]d<SIZE>[+MOD]\n") +} + +func roll(input string) { + parser := regexp.MustCompile("^([0-9]*)d([0-9]+)([+-][0-9]+)?$") + parts := parser.FindStringSubmatch(input) + if len(parts) < 2 { + usage() + return + } + dice, _ := strconv.Atoi(parts[1]) + die_size, _ := strconv.Atoi(parts[2]) + mod := 0 + if len(parts) > 3 { + mod, _ = strconv.Atoi(parts[3]) + } + if dice < 1 { + dice = 1 + } + + total := 0 + for i := 0; i < dice; i++ { + v := rand.Intn(die_size) + 1 + fmt.Printf("%d+", v) + total += v + } + total += mod + fmt.Printf("%d = %d\n", mod, total) +} + +func main() { + rand.Seed(time.Now().UTC().UnixNano()) + if len(os.Args) == 1 { + usage() + } + args := os.Args[1:] + for _, arg := range args { + roll(arg) + } +} diff --git a/roll.php b/roll.php deleted file mode 100644 index c52f762..0000000 --- a/roll.php +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env php -<?php - -function usage() { - echo "Arguments are in the format [<COUNT>]d<SIZE>[+MOD]\n"; -} - -function roll($input) { - preg_match('/([0-9]*)d([0-9]+)([+-][0-9]+)?/', $input, $matches); - if (sizeof($matches) < 2) { - usage(); - return; - } - $dice = (int)$matches[1]; - $die_size = (int)$matches[2]; - @$mod = (int)$matches[3]; - if ($dice<1) $dice = 1; - - $total = 0; - for ($i=0; $i < $dice; $i++) { - $v = mt_rand(1, $die_size); - echo $v.'+'; - $total += $v; - } - $total += $mod; - echo $mod.' = '.$total."\n"; -} - -if (sizeof($argv) == 1) { - usage(); -} -array_shift($argv); -foreach ($argv as $arg) { - roll($arg); -} |