Playing with rolls of dice or whatebbs
This commit is contained in:
parent
0bad7fe2f9
commit
5500be5264
35
algs4/src/meatballhat.com/algs4-rolls/main.go
Normal file
35
algs4/src/meatballhat.com/algs4-rolls/main.go
Normal file
@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
import (
|
||||
"meatballhat.com/algs4"
|
||||
)
|
||||
|
||||
const (
|
||||
USAGE string = "Usage: algs4-rolls <nrolls>"
|
||||
SIDES = 6
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Println(USAGE)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
nrolls, err := strconv.ParseInt(os.Args[1], 10, 32)
|
||||
if err != nil {
|
||||
fmt.Println("Wat.", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
rolls, err := algs4.Rolls(nrolls)
|
||||
|
||||
for i := 1; i <= algs4.ROLL_SIDES; i += 1 {
|
||||
fmt.Println(rolls[i])
|
||||
}
|
||||
}
|
33
algs4/src/meatballhat.com/algs4/rolls.go
Normal file
33
algs4/src/meatballhat.com/algs4/rolls.go
Normal file
@ -0,0 +1,33 @@
|
||||
package algs4
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
const ROLL_SIDES = 6
|
||||
|
||||
func Rolls(nrolls int64) ([]*Counter, error) {
|
||||
var err error
|
||||
|
||||
rolls := make([]*Counter, ROLL_SIDES+1)
|
||||
for i := 1; i <= ROLL_SIDES; i += 1 {
|
||||
rolls[i] = NewCounter(fmt.Sprintf("%d's", i))
|
||||
}
|
||||
|
||||
var result *big.Int
|
||||
randMax := big.NewInt(ROLL_SIDES)
|
||||
|
||||
for t := int64(0); t < nrolls; t += 1 {
|
||||
result, err = rand.Int(rand.Reader, randMax)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rolls[int(result.Int64())+1].Increment()
|
||||
}
|
||||
|
||||
return rolls, nil
|
||||
}
|
Loading…
Reference in New Issue
Block a user