Browse Source

[2020-12-09] Add solutions for day09

master
Elis Hirwing 9 months ago
parent
commit
230988d40a
Signed by: etu GPG Key ID: D57EFA625C9A925F
  1. 2
      Makefile
  2. 20
      day09/example.txt
  3. 1000
      day09/input.txt
  4. 41
      day09/lib.go
  5. 22
      day09/parse.go
  6. 26
      day09/solve1.go
  7. 25
      day09/solve2.go
  8. 4
      main.go

2
Makefile

@ -27,6 +27,8 @@ day08:
go run main.go day08 input
day09:
go run main.go day09 input
day10:
day11:
day12:

20
day09/example.txt

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

1000
day09/input.txt

File diff suppressed because it is too large

41
day09/lib.go

@ -0,0 +1,41 @@
package day09
import (
"sort"
)
func isSumOfPreviousNumbers(current int, previous []int) bool {
for _, n1 := range previous {
for _, n2 := range previous {
if n1+n2 == current {
return true
}
}
}
return false
}
func findAnomalySum(anomaly int, numbers []int) int {
for k1 := range numbers {
sum := 0
for k2, n2 := range numbers[k1:] {
sum += n2
if sum > anomaly {
break
}
if sum == anomaly {
targetSet := numbers[k1 : k1+k2+1]
sort.Ints(targetSet)
return targetSet[0] + targetSet[len(targetSet)-1]
}
}
}
return 0
}

22
day09/parse.go

@ -0,0 +1,22 @@
package day09
import (
"strconv"
"git.elis.nu/etu/aoc2020/utils"
)
var rows []int
func ParseFile(input string) {
// Parse file
for _, line := range utils.GetLinesFromFile("day09/" + input + ".txt") {
number, err := strconv.Atoi(line)
if err != nil {
continue
}
rows = append(rows, number)
}
}

26
day09/solve1.go

@ -0,0 +1,26 @@
package day09
import (
"log"
)
func Solve1() {
anomaly := 0
rangeSize := 25
if len(rows) == 20 {
rangeSize = 5
}
i := 0
for _, num := range rows[rangeSize:] {
if isSumOfPreviousNumbers(num, rows[i:i+rangeSize]) == false {
anomaly = num
}
i++
}
log.Printf("2020-12-09.01: Answer: %d\n", anomaly)
}

25
day09/solve2.go

@ -0,0 +1,25 @@
package day09
import (
"log"
)
func Solve2() {
anomaly := 0
rangeSize := 25
if len(rows) == 20 {
rangeSize = 5
}
i := 0
for _, num := range rows[rangeSize:] {
if isSumOfPreviousNumbers(num, rows[i:i+rangeSize]) == false {
anomaly = num
}
i++
}
log.Printf("2020-12-09.02: Answer: %d\n", findAnomalySum(anomaly, rows))
}

4
main.go

@ -12,6 +12,7 @@ import (
"git.elis.nu/etu/aoc2020/day06"
"git.elis.nu/etu/aoc2020/day07"
"git.elis.nu/etu/aoc2020/day08"
"git.elis.nu/etu/aoc2020/day09"
"git.elis.nu/etu/aoc2020/utils"
)
@ -44,5 +45,8 @@ func main() {
case "day08":
utils.Perf("2020-12-08", day08.ParseFile, day08.Solve1, day08.Solve2)
case "day09":
utils.Perf("2020-12-09", day09.ParseFile, day09.Solve1, day09.Solve2)
}
}

Loading…
Cancel
Save