adventofcode/2018/internal/calibration/calibration.go

39 lines
867 B
Go

package calibration
import (
"bufio"
"os"
"strconv"
)
type Set map[int]struct{}
// ScanFrequencies iterates over a list of frequencies (provided as an open
// file handle), compares against a list of frequencies already seen and a 'current' frequency counter,
// and returns `true` when a duplicate frequency is found. Integer value returned is the new, adjusted frequency
func ScanFrequencies(freqFile string, seen *Set, frequency int) (int, bool) {
file, err := os.Open(os.Args[1])
if err != nil {
panic(err)
}
duplicateFound := false
scanner := bufio.NewScanner(file)
for scanner.Scan() {
y, err := strconv.Atoi(scanner.Text())
if err != nil {
panic(err)
}
frequency += y
if _, ok := (*seen)[frequency]; ok {
duplicateFound = true
break
}
(*seen)[frequency] = struct{}{}
}
file.Close()
return frequency, duplicateFound
}