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

This commit is contained in:
Anna Rose Wiggins 2018-12-01 22:13:08 -05:00
parent 333321cfd7
commit 01f53ae30c
No known key found for this signature in database
GPG key ID: 8D9ACA841015C59A
3 changed files with 44 additions and 19 deletions

View file

@ -1,56 +0,0 @@
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
type Set map[int]struct{}
// Provide a filename as input, get the result on stdout
func main() {
x := 0
found := false
seen := Set{0: struct{}{}}
for {
x, found = ScanFrequencies(os.Args[1], &seen, x)
if found {
break
}
fmt.Println("All frequencies scanned, repeating...")
}
fmt.Println("Repeat frequency detected, calibration complete: ", x)
}
// 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
}