day 7 in the books

This commit is contained in:
David 2021-12-07 09:19:13 -05:00
parent 55383aeedf
commit 8e68234caa
1 changed files with 111 additions and 0 deletions

111
07/main.go Normal file
View File

@ -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)
}