Re-implement a solution for the first day 1 puzzle, move common code into a library package.

This commit is contained in:
2018-12-01 22:13:08 -05:00
parent 333321cfd7
commit 01f53ae30c
3 changed files with 44 additions and 19 deletions

View File

@ -0,0 +1,38 @@
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
}