-
Notifications
You must be signed in to change notification settings - Fork 3
/
day02.go
127 lines (110 loc) · 2.18 KB
/
day02.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Package main provides ...
package main
import (
"bufio"
"errors"
"fmt"
"log"
"os"
"strconv"
"strings"
)
func AddOne(x int) int {
return x + 1
}
// Parse (Filename) -> Spreadsheet
func Parse(filename string) [][]int {
spreadSheet := make([][]int, 0)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
numsThisLine, err := sliceAtoi(strings.Fields(scanner.Text()))
if err != nil {
return spreadSheet
}
spreadSheet = append(spreadSheet, numsThisLine)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return spreadSheet
}
// sliceAtoi (Slice of strings) -> Slice of Ints
func sliceAtoi(strings []string) ([]int, error) {
ints := make([]int, 0)
for _, str := range strings {
num, err := strconv.Atoi(str)
if err != nil {
return ints, err
}
ints = append(ints, num)
}
return ints, nil
}
// Part1 : Sum up all the checksums of a spreadsheet
func Part1(spreadSheet [][]int) int {
checksums := 0
for _, row := range spreadSheet {
checksum := Checksum(row)
checksums += checksum
}
return checksums
}
func Part2(spreadSheet [][]int) int {
checksums := 0
for _, row := range spreadSheet {
checksum, err := DivChecksum(row)
if err != nil {
return checksums
}
checksums += checksum
}
return checksums
}
func Checksum(row []int) int {
min, max := MinMax(row)
return max - min
}
func MinMax(row []int) (int, int) {
var min int = row[0]
var max int = row[0]
for _, value := range row {
if value < min {
min = value
}
if value > max {
max = value
}
}
return min, max
}
func DivChecksum(row []int) (int, error) {
for xi, x := range row {
for yi, y := range row {
if xi == yi {
continue
}
d := float64(x) / float64(y)
if isIntegral(d) {
return int(d), nil
}
}
}
return 0, errors.New("Couldn't find two numbers that divide evenly")
}
func isIntegral(val float64) bool {
return val == float64(int(val))
}
func main() {
spreadSheet := Parse("../input.txt")
fmt.Println("Part1")
checkSum := Part1(spreadSheet)
fmt.Println(checkSum)
fmt.Println("Part2")
divCheckSum := Part2(spreadSheet)
fmt.Println(divCheckSum)
}