Fixing a few places where I was using "crypto/rand"

to use "math/rand" with a proper seeding instead.
This commit is contained in:
Dan Buch 2012-12-20 00:34:24 -05:00
parent 7a40632ca8
commit e81b35471e
2 changed files with 10 additions and 27 deletions

View File

@ -1,12 +1,12 @@
package main package main
import ( import (
"crypto/rand"
"fmt" "fmt"
"math" "math"
"math/big" "math/rand"
"os" "os"
"strconv" "strconv"
"time"
) )
import ( import (
@ -21,7 +21,9 @@ func main() {
os.Exit(1) 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 { if err != nil {
fmt.Println("Wat.", err) fmt.Println("Wat.", err)
os.Exit(2) os.Exit(2)
@ -30,16 +32,8 @@ func main() {
heads := algs4.NewCounter("heads") heads := algs4.NewCounter("heads")
tails := algs4.NewCounter("tails") tails := algs4.NewCounter("tails")
randMax := big.NewInt(2) for t := 0; t < nflips; t++ {
if rand.Float64() > 0.5 {
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 {
heads.Increment() heads.Increment()
} else { } else {
tails.Increment() tails.Increment()

View File

@ -1,32 +1,21 @@
package algs4 package algs4
import ( import (
"crypto/rand"
"fmt" "fmt"
"math/big"
) )
const ROLL_SIDES = 6 const ROLL_SIDES = 6
func Rolls(nrolls int64) ([]*Counter, error) { func Rolls(nrolls int64) ([]*Counter, error) {
var err error
rolls := make([]*Counter, ROLL_SIDES+1) rolls := make([]*Counter, ROLL_SIDES+1)
for i := 1; i <= ROLL_SIDES; i += 1 { for i := 1; i <= ROLL_SIDES; i += 1 {
rolls[i] = NewCounter(fmt.Sprintf("%d's", i)) rolls[i] = NewCounter(fmt.Sprintf("%d's", i))
} }
var result *big.Int randMax := float64(ROLL_SIDES)
randMax := big.NewInt(ROLL_SIDES)
for t := int64(0); t < nrolls; t += 1 { for t := int64(0); t < nrolls; t++ {
result, err = rand.Int(rand.Reader, randMax) rolls[int(RandomUniform(float64(0.0), randMax))+1].Increment()
if err != nil {
return nil, err
}
rolls[int(result.Int64())+1].Increment()
} }
return rolls, nil return rolls, nil