Implementing the "RandomSeq" example

with supporting implementation of `StdRandom.uniform`
This commit is contained in:
Dan Buch 2012-12-19 22:58:37 -05:00
parent 6ebbf04980
commit 9a1c045581
3 changed files with 58 additions and 1 deletions

View File

@ -4,7 +4,8 @@ TARGETS := \
$(REPO_BASE)/algs4-binarysearch \
$(REPO_BASE)/algs4-flips \
$(REPO_BASE)/algs4-gcd \
$(REPO_BASE)/algs4-rolls
$(REPO_BASE)/algs4-rolls \
$(REPO_BASE)/algs4-randomseq
test: build
go test -x $(TARGETS)

View File

@ -0,0 +1,42 @@
package main
import (
"errors"
"fmt"
"os"
"strconv"
)
import (
"github.com/meatballhat/box-o-sand/algs4/src/go/algs4"
)
func die(err error) {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
os.Exit(1)
}
func main() {
if len(os.Args) < 4 {
die(errors.New("We need an int and two floats!"))
}
n, err := strconv.Atoi(os.Args[1])
if err != nil {
die(err)
}
lo, err := strconv.ParseFloat(os.Args[2], 32)
if err != nil {
die(err)
}
hi, err := strconv.ParseFloat(os.Args[3], 32)
if err != nil {
die(err)
}
for i := 0; i < n; i++ {
x := algs4.RandomUniform(lo, hi)
fmt.Printf("%.2f\n", x)
}
}

View File

@ -0,0 +1,14 @@
package algs4
import (
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func RandomUniform(min, max float64) float64 {
return rand.Float64()*(max-min) + min
}