Cleaning up rolls implementation

to be a bit more idiomatic, I suppose.
This commit is contained in:
Dan Buch 2012-12-20 08:36:35 -05:00
parent e81b35471e
commit 5bf03a1a40
2 changed files with 21 additions and 16 deletions

View File

@ -11,25 +11,27 @@ import (
)
const (
USAGE string = "Usage: algs4-rolls <nrolls>"
USAGE = "Usage: algs4-rolls <nrolls>"
SIDES = 6
)
func die(err error) {
fmt.Println("Wat.", err)
os.Exit(2)
}
func main() {
if len(os.Args) < 2 {
fmt.Println(USAGE)
os.Exit(1)
}
nrolls, err := strconv.ParseInt(os.Args[1], 10, 32)
nrolls, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println("Wat.", err)
os.Exit(2)
die(err)
}
rolls, err := algs4.Rolls(nrolls)
for i := 1; i <= algs4.ROLL_SIDES; i += 1 {
fmt.Println(rolls[i])
for _, roll := range algs4.Rolls(nrolls) {
fmt.Println(roll)
}
}

View File

@ -6,17 +6,20 @@ import (
const ROLL_SIDES = 6
func Rolls(nrolls int64) ([]*Counter, error) {
rolls := make([]*Counter, ROLL_SIDES+1)
for i := 1; i <= ROLL_SIDES; i += 1 {
rolls[i] = NewCounter(fmt.Sprintf("%d's", i))
func Rolls(nrolls int) []*Counter {
var rolls []*Counter
for i := 0; i < ROLL_SIDES; i++ {
rolls = append(rolls, NewCounter(fmt.Sprintf("%d's", i+1)))
}
randMax := float64(ROLL_SIDES)
zero := float64(0.0)
for t := int64(0); t < nrolls; t++ {
rolls[int(RandomUniform(float64(0.0), randMax))+1].Increment()
for t := 0; t < nrolls; t++ {
result := int(RandomUniform(zero, randMax))
rolls[result].Increment()
}
return rolls, nil
return rolls
}