From 9a1c045581616494b1db8c53f05f2a813f0ecf58 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Wed, 19 Dec 2012 22:58:37 -0500 Subject: [PATCH] Implementing the "RandomSeq" example with supporting implementation of `StdRandom.uniform` --- algs4/{ => src/go}/Makefile | 3 +- algs4/src/go/algs4-randomseq/main.go | 42 ++++++++++++++++++++++++++++ algs4/src/go/algs4/random.go | 14 ++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) rename algs4/{ => src/go}/Makefile (86%) create mode 100644 algs4/src/go/algs4-randomseq/main.go create mode 100644 algs4/src/go/algs4/random.go diff --git a/algs4/Makefile b/algs4/src/go/Makefile similarity index 86% rename from algs4/Makefile rename to algs4/src/go/Makefile index e611588..58d819a 100644 --- a/algs4/Makefile +++ b/algs4/src/go/Makefile @@ -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) diff --git a/algs4/src/go/algs4-randomseq/main.go b/algs4/src/go/algs4-randomseq/main.go new file mode 100644 index 0000000..89130a8 --- /dev/null +++ b/algs4/src/go/algs4-randomseq/main.go @@ -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) + } +} diff --git a/algs4/src/go/algs4/random.go b/algs4/src/go/algs4/random.go new file mode 100644 index 0000000..ce68830 --- /dev/null +++ b/algs4/src/go/algs4/random.go @@ -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 +}