Starting work on the Interval2D example

and filling in drawing library along the way.
This commit is contained in:
Dan Buch 2012-12-20 10:47:12 -05:00
parent 5bf03a1a40
commit c2dc9cfe02
6 changed files with 154 additions and 1 deletions

View File

@ -6,7 +6,8 @@ TARGETS := \
$(REPO_BASE)/algs4-gcd \ $(REPO_BASE)/algs4-gcd \
$(REPO_BASE)/algs4-rolls \ $(REPO_BASE)/algs4-rolls \
$(REPO_BASE)/algs4-randomseq \ $(REPO_BASE)/algs4-randomseq \
$(REPO_BASE)/algs4-average $(REPO_BASE)/algs4-average \
$(REPO_BASE)/algs4-interval2d
test: build test: build
go test -x $(TARGETS) go test -x $(TARGETS)

View File

@ -0,0 +1,73 @@
package main
import (
"errors"
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
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) < 6 {
die(errors.New("We need 4 floats and an int!"))
}
rand.Seed(time.Now().UTC().UnixNano())
xlo, err := strconv.ParseFloat(os.Args[1], 32)
if err != nil {
die(err)
}
xhi, err := strconv.ParseFloat(os.Args[2], 32)
if err != nil {
die(err)
}
ylo, err := strconv.ParseFloat(os.Args[3], 32)
if err != nil {
die(err)
}
yhi, err := strconv.ParseFloat(os.Args[4], 32)
if err != nil {
die(err)
}
npoints, err := strconv.Atoi(os.Args[5])
if err != nil {
die(err)
}
xint := algs4.NewInterval1D(xlo, xhi)
yint := algs4.NewInterval1D(ylo, yhi)
box := algs4.NewInterval2D(xint, yint, nil)
box.Draw()
c := algs4.NewCounter("hits")
for t := 0; t < npoints; t++ {
x := rand.Float64()
y := rand.Float64()
p := algs4.NewPoint2D(x, y, nil)
if box.Contains(p) {
c.Increment()
} else {
p.Draw()
}
}
algs4.Draw()
fmt.Println(c)
fmt.Printf("area = %.2f\n", box.Area())
}

View File

@ -0,0 +1,12 @@
package algs4
var (
DefaultCanvas = &Canvas{}
)
type Canvas struct {
}
func Draw() {
return
}

View File

@ -0,0 +1,13 @@
package algs4
type Interval1D struct {
Lo float64
Hi float64
}
func NewInterval1D(lo, hi float64) *Interval1D {
return &Interval1D{
Lo: lo,
Hi: hi,
}
}

View File

@ -0,0 +1,31 @@
package algs4
type Interval2D struct {
Xint *Interval1D
Yint *Interval1D
Canvas *Canvas
}
func NewInterval2D(xint, yint *Interval1D, canvas *Canvas) *Interval2D {
if canvas == nil {
canvas = DefaultCanvas
}
return &Interval2D{
Xint: xint,
Yint: yint,
Canvas: canvas,
}
}
func (me *Interval2D) Contains(p *Point2D) bool {
return false
}
func (me *Interval2D) Draw() {
return
}
func (me *Interval2D) Area() float64 {
return float64(0)
}

View File

@ -0,0 +1,23 @@
package algs4
type Point2D struct {
X float64
Y float64
Canvas *Canvas
}
func NewPoint2D(x, y float64, canvas *Canvas) *Point2D {
if canvas == nil {
canvas = DefaultCanvas
}
return &Point2D{
X: x,
Y: y,
Canvas: canvas,
}
}
func (me *Point2D) Draw() {
return
}