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

View File

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