Created
February 20, 2024 04:44
-
-
Save samebchase/47f14464766c8ec196cb22c63a6326e9 to your computer and use it in GitHub Desktop.
One Billion Rows Challenge - Baseline solution in Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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