-
Notifications
You must be signed in to change notification settings - Fork 0
/
r0.go
102 lines (90 loc) · 1.83 KB
/
r0.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"slices"
"strconv"
)
type Stats struct {
Max float64
Min float64
Sum float64
Count int
}
func (s *Stats) Add(reading float64) {
if reading > s.Max {
s.Max = reading
}
if reading < s.Min {
s.Min = reading
}
s.Sum += reading
s.Count++
}
func (s *Stats) Mean() float64 {
return s.Sum / float64(s.Count)
}
func (s Stats) String() string {
return fmt.Sprintf("%.1f/%.1f/%.1f", s.Min, s.Mean(), s.Max)
}
func r0(measurementsPath string) {
file, err := os.Open(measurementsPath)
if err != nil {
log.Fatalf("Could not open %s: %s", measurementsPath, err)
}
defer file.Close()
stationStats := make(map[string]Stats)
csvReader := csv.NewReader(file)
csvReader.Comma = ';'
csvReader.Comment = '#'
for {
row, err := csvReader.Read()
if row == nil && err == io.EOF {
break
}
if err != nil {
log.Fatalf("Could not read row from %s: %s", measurementsPath, err)
}
if len(row) != 2 {
log.Fatalf(
"Data in %s is malformed. There should be exactly 2 columns, read row %v",
measurementsPath,
row,
)
}
station := row[0]
reading, err := strconv.ParseFloat(row[1], 64)
if err != nil {
log.Fatalf("Could not convert reading '%s' to float64", row[1])
}
stats, ok := stationStats[station]
if !ok {
stationStats[station] = Stats{
Max: reading,
Min: reading,
Sum: reading,
Count: 1,
}
} else {
stats.Add(reading)
stationStats[station] = stats
}
}
stations := make([]string, 0, len(stationStats))
for station := range stationStats {
stations = append(stations, station)
}
slices.Sort(stations)
fmt.Print("{")
for i, station := range stations {
stats := stationStats[station]
fmt.Printf("%s=%s", station, stats)
if i != len(stations)-1 {
fmt.Print(", ")
}
}
fmt.Println("}")
}