AdventOfCode2021/07/main.go
2021-12-07 09:19:13 -05:00

112 lines
2.0 KiB
Go

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