From c066cf155d17d885561d6ccc07c870f2841bebf6 Mon Sep 17 00:00:00 2001 From: Anna Wiggins Date: Sat, 1 Dec 2018 21:40:48 -0500 Subject: [PATCH] Day 1 completed. --- 2018/day01.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 2018/day01.go diff --git a/2018/day01.go b/2018/day01.go new file mode 100644 index 0000000..fa4e26d --- /dev/null +++ b/2018/day01.go @@ -0,0 +1,56 @@ +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 +}