Skip to content

Instantly share code, notes, and snippets.

@samebchase
Created February 20, 2024 04:44
Show Gist options
  • Save samebchase/47f14464766c8ec196cb22c63a6326e9 to your computer and use it in GitHub Desktop.
Save samebchase/47f14464766c8ec196cb22c63a6326e9 to your computer and use it in GitHub Desktop.
One Billion Rows Challenge - Baseline solution in Go.
package main
import (
"bufio"
"flag"
"log/slog"
"os"
"strconv"
"strings"
)
type Stat struct {
Min float64
Avg float64
Max float64
Count int64
}
func computeStats(results *map[string]Stat, country string, measurement float64) {
if stat, ok := (*results)[country]; !ok {
(*results)[country] = Stat{measurement, measurement, measurement, 1}
} else {
var min float64
if measurement < stat.Min {
min = measurement
} else {
min = stat.Min
}
avg := (measurement - stat.Avg) / float64(stat.Count)
var max float64
if measurement > stat.Max {
max = measurement
} else {
max = stat.Max
}
count := stat.Count + 1
(*results)[country] = Stat{min, avg, max, count}
}
}
func generateStats(path string) {
file, err := os.Open(path)
if err != nil {
slog.Error(err.Error())
}
defer file.Close()
scanner := bufio.NewScanner(file)
results := make(map[string]Stat)
for scanner.Scan() {
splits := strings.Split(scanner.Text(), ";")
country := splits[0]
measurement, err := strconv.ParseFloat(splits[1], 64)
if err != nil {
slog.Error(err.Error())
}
computeStats(&results, country, measurement)
}
if err := scanner.Err(); err != nil {
slog.Error(err.Error())
}
printStats(&results)
}
func printStats(results *map[string]Stat) {
slog.Info("Final value", "temps", *results)
}
func main() {
tempMeasurementsFilePath := flag.String("input", "some-requirements.txt", "Temperature measurements file.")
flag.Parse()
generateStats(*tempMeasurementsFilePath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment