-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (50 loc) · 1009 Bytes
/
main.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
package main
import (
input "aoc2020/inpututils"
"errors"
"fmt"
)
func main() {
fmt.Println("--- Part One ---")
fmt.Println(Part1("input.txt"))
fmt.Println("--- Part Two ---")
fmt.Println(Part2("input.txt"))
}
// create set type as Go doesn't have one
type set map[int]struct{}
func (s set) add(n int) {
s[n] = struct{}{}
}
func (s set) has(n int) bool {
_, ok := s[n]
return ok
}
func Part1(filename string) int {
nums := input.ReadNumbers(filename)
product, err := twoSum(nums, 2020)
if err != nil {
return -1
}
return product
}
func Part2(filename string) int {
nums := input.ReadNumbers(filename)
for i := 0; i < len(nums)-2; i += 1 {
num := nums[i]
product, err := twoSum(nums[i+1:], 2020-num)
if err == nil {
return product * num
}
}
return -1
}
func twoSum(ints []int, target int) (int, error) {
seen := set{}
for _, i := range ints {
if seen.has(target - i) {
return (target - i) * i, nil
}
seen.add(i)
}
return -1, errors.New("No solution")
}