-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday01.go
73 lines (66 loc) · 1.07 KB
/
day01.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Package main provides ...
package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func Fuel(x int) int {
return x/3 - 2
}
func TotalFuel(fuel int) int {
total := 0
for {
fuel = Fuel(fuel)
if fuel <= 0 {
break
}
total += fuel
}
return total
}
func Parse(filename string) []int {
lines := make([]int, 0)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
num, err := strconv.Atoi(strings.TrimSpace(line))
if err != nil {
log.Fatal(err)
}
lines = append(lines, num)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return lines
}
func Part1(nums []int) int {
total := 0
for _, num := range nums {
total += Fuel(num)
}
return total
}
func Part2(nums []int) int {
total := 0
for _, num := range nums {
total += TotalFuel(num)
}
return total
}
func main() {
nums := Parse("../input.txt")
fmt.Println("AOC 2019 Day 01:")
fmt.Println("Part1:")
fmt.Println(Part1(nums))
fmt.Println("Part2:")
fmt.Println(Part2(nums))
}