advent-of-code/2019/01/day1.go

41 lines
637 B
Go
Raw Normal View History

2019-12-01 19:25:14 +01:00
package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func main() {
inFile, _ := ioutil.ReadFile("input")
lines := strings.Split(string(inFile), "\n")
2019-12-01 20:26:37 +01:00
part1, part2 := solve(lines)
fmt.Printf("Part 1: %d\n", part1)
fmt.Printf("Part 2: %d\n", part2)
2019-12-01 19:25:14 +01:00
}
2019-12-01 20:26:37 +01:00
func solve(lines []string) (int, int) {
2019-12-01 19:25:14 +01:00
fuel := 0
2019-12-01 20:26:37 +01:00
fuelRec := 0
2019-12-01 19:25:14 +01:00
for _, line := range lines {
mass, _ := strconv.Atoi(line)
fuel += cost(mass)
2019-12-01 20:26:37 +01:00
fuelRec += costRec(mass, 0)
2019-12-01 19:25:14 +01:00
}
2019-12-01 20:26:37 +01:00
return fuel, fuelRec
2019-12-01 19:25:14 +01:00
}
func cost(mass int) int {
return mass/3 - 2
}
func costRec(mass int, acc int) int {
c := cost(mass)
if c <= 0 {
return acc
}
return costRec(c, acc+c)
}