Browse Source

2020 Day 9 Complete

master
Brian Buller 11 months ago
parent
commit
f1bd9923cb
  1. 2
      2020/day08/main.go
  2. 1000
      2020/day09/input
  3. 88
      2020/day09/main.go
  4. 20
      2020/day09/testinput

2
2020/day08/main.go

@ -8,7 +8,7 @@ import (
)
func main() {
fmt.Println("# Day 7")
fmt.Println("# Day 8")
inp := h.StdinToStringSlice()
FixProg(inp)
}

1000
2020/day09/input

File diff suppressed because it is too large

88
2020/day09/main.go

@ -0,0 +1,88 @@
package main
import (
"errors"
"fmt"
h "git.bullercodeworks.com/brian/adventofcode/helpers"
)
func main() {
fmt.Println("# Day 9")
inp := h.StdinToIntSlice()
rogue, err := FindRogueNumber(inp)
if err != nil {
fmt.Println(err.Error())
return
}
answer, err := FindWeakness(rogue, inp)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Answer:", answer)
}
func FindRogueNumber(inp []int) (int, error) {
for k, v := range inp {
if k >= 25 {
if !ContainsPairFor(v, inp[k-25:k]) {
return v, nil
}
}
}
return -1, errors.New("All numbers fit")
}
func ContainsPairFor(target int, inp []int) bool {
for i := 0; i < len(inp)-1; i++ {
for k := i + 1; k < len(inp); k++ {
if inp[i]+inp[k] == target {
return true
}
}
}
return false
}
func FindWeakness(target int, inp []int) (int, error) {
for i := 0; i < len(inp)-1; i++ {
for k := i + 1; k < len(inp); k++ {
sum := GetSumForRange(inp[i:k])
if sum == target {
return FindSmallest(inp[i:k]) + FindLargest(inp[i:k]), nil
} else if sum > target {
break
}
}
}
return -1, errors.New("No weakness found")
}
func GetSumForRange(inp []int) int {
var ret int
for k := range inp {
ret = ret + inp[k]
}
return ret
}
func FindSmallest(inp []int) int {
ret := inp[0]
for k := range inp {
if inp[k] < ret {
ret = inp[k]
}
}
return ret
}
func FindLargest(inp []int) int {
ret := inp[0]
for k := range inp {
if inp[k] > ret {
ret = inp[k]
}
}
return ret
}

20
2020/day09/testinput

@ -0,0 +1,20 @@
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
Loading…
Cancel
Save