Implementing the "RandomSeq" example

with supporting implementation of `StdRandom.uniform`
cat-town
Dan Buch 12 years ago
parent 6ebbf04980
commit 9a1c045581

@ -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)

@ -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)
}
}

@ -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
}
Loading…
Cancel
Save