From 8e68234caa54cf0139d69f8a469b27b1bda46ec6 Mon Sep 17 00:00:00 2001 From: David Ashby Date: Tue, 7 Dec 2021 09:19:13 -0500 Subject: [PATCH] day 7 in the books --- 07/main.go | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 07/main.go diff --git a/07/main.go b/07/main.go new file mode 100644 index 0000000..d8aaa46 --- /dev/null +++ b/07/main.go @@ -0,0 +1,111 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" + "time" +) + +func main() { + start := time.Now() + partOne() + duration := time.Since(start) + partTwo() + duration2 := time.Since(start) + fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration) +} + +func makeScanner(test bool) *bufio.Scanner { + var f *os.File + if test { + f, _ = os.Open("inputs/testinput") + } else { + f, _ = os.Open("inputs/input") + } + reader := bufio.NewReader(f) + return bufio.NewScanner(reader) +} + +func mustAtoi(line string) int { + i, _ := strconv.Atoi(line) + return i +} + +func fuelCostPartOne(crabs []int, column int) int { + var totalFuel int + for _, v := range crabs { + if column < v { + totalFuel += v - column + } + if column > v { + totalFuel += column - v + } + } + return totalFuel +} + +func fuelCostPartTwo(crabs []int, column int) int { + var totalFuel int + for _, v := range crabs { + if column < v { + totalFuel += ((v - column) * ((v - column) + 1)) / 2 + } + if column > v { + totalFuel += ((column - v) * ((column - v) + 1)) / 2 + } + } + return totalFuel +} + +func partOne() { + scanner := makeScanner(false) + + // just a single line today + scanner.Scan() + input := strings.Split(scanner.Text(), ",") + crabs := []int{} + var max int + for _, v := range input { + crab := mustAtoi(v) + crabs = append(crabs, crab) + if max < crab { + max = crab + } + } + lowestFuel := 1000000000 // some initial awful max fuel cost + for i := 0; i <= max; i++ { + cost := fuelCostPartOne(crabs, i) + if cost < lowestFuel { + lowestFuel = cost + } + } + fmt.Println(lowestFuel) +} + +func partTwo() { + scanner := makeScanner(false) + + // just a single line today + scanner.Scan() + input := strings.Split(scanner.Text(), ",") + crabs := []int{} + var max int + for _, v := range input { + crab := mustAtoi(v) + crabs = append(crabs, crab) + if max < crab { + max = crab + } + } + lowestFuel := 1000000000 // some initial awful max fuel cost + for i := 0; i <= max; i++ { + cost := fuelCostPartTwo(crabs, i) + if cost < lowestFuel { + lowestFuel = cost + } + } + fmt.Println(lowestFuel) +}