From e81b35471e4b28692470a1b65954e9d1b81d9ef4 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Thu, 20 Dec 2012 00:34:24 -0500 Subject: [PATCH] Fixing a few places where I was using "crypto/rand" to use "math/rand" with a proper seeding instead. --- algs4/src/go/algs4-flips/main.go | 20 +++++++------------- algs4/src/go/algs4/rolls.go | 17 +++-------------- 2 files changed, 10 insertions(+), 27 deletions(-) diff --git a/algs4/src/go/algs4-flips/main.go b/algs4/src/go/algs4-flips/main.go index a3ff51d..ac9f79c 100644 --- a/algs4/src/go/algs4-flips/main.go +++ b/algs4/src/go/algs4-flips/main.go @@ -1,12 +1,12 @@ package main import ( - "crypto/rand" "fmt" "math" - "math/big" + "math/rand" "os" "strconv" + "time" ) import ( @@ -21,7 +21,9 @@ func main() { os.Exit(1) } - nflips, err := strconv.ParseInt(os.Args[1], 10, 32) + rand.Seed(time.Now().UTC().UnixNano()) + + nflips, err := strconv.Atoi(os.Args[1]) if err != nil { fmt.Println("Wat.", err) os.Exit(2) @@ -30,16 +32,8 @@ func main() { heads := algs4.NewCounter("heads") tails := algs4.NewCounter("tails") - randMax := big.NewInt(2) - - for t := int64(0); t < nflips; t += int64(1) { - n, err := rand.Int(rand.Reader, randMax) - if err != nil { - fmt.Println("Ugh:", err) - os.Exit(4) - } - - if n.Int64() < 1 { + for t := 0; t < nflips; t++ { + if rand.Float64() > 0.5 { heads.Increment() } else { tails.Increment() diff --git a/algs4/src/go/algs4/rolls.go b/algs4/src/go/algs4/rolls.go index ead8eac..7c8e25f 100644 --- a/algs4/src/go/algs4/rolls.go +++ b/algs4/src/go/algs4/rolls.go @@ -1,32 +1,21 @@ 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 - } + randMax := float64(ROLL_SIDES) - rolls[int(result.Int64())+1].Increment() + for t := int64(0); t < nrolls; t++ { + rolls[int(RandomUniform(float64(0.0), randMax))+1].Increment() } return rolls, nil