diff --git a/algs4/src/go/algs4-rolls/main.go b/algs4/src/go/algs4-rolls/main.go index fec8921..ea89e5e 100644 --- a/algs4/src/go/algs4-rolls/main.go +++ b/algs4/src/go/algs4-rolls/main.go @@ -11,25 +11,27 @@ import ( ) const ( - USAGE string = "Usage: algs4-rolls " - SIDES = 6 + USAGE = "Usage: algs4-rolls " + 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) } } diff --git a/algs4/src/go/algs4/rolls.go b/algs4/src/go/algs4/rolls.go index 7c8e25f..577058c 100644 --- a/algs4/src/go/algs4/rolls.go +++ b/algs4/src/go/algs4/rolls.go @@ -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 }