2021 - Day 6
This commit is contained in:
parent
e802f62a1e
commit
9d32b5ac1a
9
2021/6/go.mod
Normal file
9
2021/6/go.mod
Normal file
|
@ -0,0 +1,9 @@
|
|||
module AoC/2021/6
|
||||
|
||||
require AoC/2021/common v0.0.0
|
||||
|
||||
require github.com/joho/godotenv v1.4.0 // indirect
|
||||
|
||||
replace AoC/2021/common v0.0.0 => ../common
|
||||
|
||||
go 1.17
|
2
2021/6/go.sum
Normal file
2
2021/6/go.sum
Normal file
|
@ -0,0 +1,2 @@
|
|||
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
|
||||
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
92
2021/6/main.go
Normal file
92
2021/6/main.go
Normal file
|
@ -0,0 +1,92 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
aoc "AoC/2021/common"
|
||||
"bufio"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
aoc := aoc.New(2021, 6)
|
||||
|
||||
aoc.Test(`3,4,3,1,2`, []int{5934, 26984457539})
|
||||
|
||||
// This is a very naive solution, it works for part 1 but not for part 2
|
||||
aoc.Solution(1, func (input *bufio.Scanner) int {
|
||||
var fish []int
|
||||
|
||||
input.Scan()
|
||||
line := input.Text()
|
||||
numbers := strings.Split(line, ",")
|
||||
|
||||
for _, str := range numbers {
|
||||
n, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fish = append(fish, n)
|
||||
}
|
||||
|
||||
days := 80
|
||||
for day := 1; day <= days; day++ {
|
||||
add := 0
|
||||
|
||||
for i := range fish {
|
||||
if fish[i] == 0 {
|
||||
add++
|
||||
fish[i] = 6
|
||||
} else {
|
||||
fish[i]--
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < add; i++ {
|
||||
fish = append(fish, 8)
|
||||
}
|
||||
}
|
||||
|
||||
return len(fish)
|
||||
})
|
||||
|
||||
// This is a much more elegant solution, it can also be used to solve part 1
|
||||
aoc.Solution(2, func (input *bufio.Scanner) int {
|
||||
fish := make(map[int]int)
|
||||
input.Scan()
|
||||
line := input.Text()
|
||||
numbers := strings.Split(line, ",")
|
||||
|
||||
for _, str := range numbers {
|
||||
n, err := strconv.Atoi(str)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
fish[n]++
|
||||
}
|
||||
|
||||
days := 256
|
||||
for day := 1; day <= days; day++ {
|
||||
temp := make(map[int]int)
|
||||
|
||||
for n, c := range fish {
|
||||
if n == 0 {
|
||||
temp[8] += c
|
||||
temp[6] += c
|
||||
} else {
|
||||
temp[n-1] += c
|
||||
}
|
||||
}
|
||||
|
||||
fish = temp
|
||||
}
|
||||
|
||||
sum := 0
|
||||
for _, c := range fish {
|
||||
sum += c
|
||||
}
|
||||
|
||||
return sum
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user