Playing with counters and flips

cat-town
Dan Buch 12 years ago
parent 9cb1be13fe
commit 0bad7fe2f9

@ -0,0 +1,55 @@
package main
import (
"crypto/rand"
"fmt"
"math"
"math/big"
"os"
"strconv"
)
import (
"meatballhat.com/algs4"
)
const USAGE string = "Usage: algs4-flips <nflips>"
func main() {
if len(os.Args) < 2 {
fmt.Println(USAGE)
os.Exit(1)
}
nflips, err := strconv.ParseInt(os.Args[1], 10, 32)
if err != nil {
fmt.Println("Wat.", err)
os.Exit(2)
}
heads := algs4.NewCounter("heads")
tails := algs4.NewCounter("tails")
randMax := big.NewInt(2)
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()
} else {
tails.Increment()
}
}
fmt.Println(heads)
fmt.Println(tails)
d := heads.Tally() - tails.Tally()
fmt.Printf("delta: %d\n", int(math.Abs(float64(d))))
}

@ -0,0 +1,37 @@
package algs4
import (
"fmt"
)
type Counter struct {
name string
count int
}
func NewCounter(name string) *Counter {
counter := &Counter{}
counter.name = name
return counter
}
func (c *Counter) Increment() {
c.count += 1
}
func (c *Counter) Tally() int {
return c.count
}
func (c *Counter) String() string {
return fmt.Sprintf("%d %s", c.count, c.name)
}
func (c *Counter) Cmp(other *Counter) int {
if c.count < other.count {
return -1
} else if c.count > other.count {
return 1
}
return 0
}
Loading…
Cancel
Save