Skip to content

Instantly share code, notes, and snippets.

@cirias
Last active April 3, 2020 08:08
Show Gist options
  • Save cirias/f2d1d11922595f02f1e8ec9b0d840e2c to your computer and use it in GitHub Desktop.
Save cirias/f2d1d11922595f02f1e8ec9b0d840e2c to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/pkg/errors"
)
func main() {
ns, err := parseNumbers(os.Stdin)
if err != nil {
log.Fatalln(err)
}
min, max := minmax(ns)
split := 10
step := (max - min) / float32(split)
buckets := make([]int, 0, split+1)
for i := 0; i <= split; i++ {
count := countWithin(ns, min+step*float32(i), min+step*float32(i+1))
buckets = append(buckets, count)
}
maxCount := 0
for _, count := range buckets {
if count > maxCount {
maxCount = count
}
}
barSize := 30
for i, count := range buckets {
bar := strings.Repeat("=", barSize*count/maxCount)
fmt.Printf("[%.2f, %.2f)\t%d\t%s\n", min+step*float32(i), min+step*float32(i+1), count, bar)
}
}
func countWithin(ns []float32, min, max float32) int {
count := 0
for _, n := range ns {
if n >= min && n < max {
count++
}
}
return count
}
func minmax(ns []float32) (float32, float32) {
if len(ns) == 0 {
return 0, 0
}
min, max := ns[0], ns[0]
for _, n := range ns[1:] {
if n < min {
min = n
}
if n > max {
max = n
}
}
return min, max
}
func parseNumbers(r io.Reader) ([]float32, error) {
ns := make([]float32, 0)
var n float32
scanner := bufio.NewScanner(r)
for scanner.Scan() {
fmt.Sscanf(scanner.Text(), "%f", &n)
ns = append(ns, n)
}
if err := scanner.Err(); err != nil {
return nil, errors.Wrapf(err, "could not scan")
}
return ns, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment