2021 - Day 7
This commit is contained in:
parent
9d32b5ac1a
commit
4d574e294f
9
2021/7/go.mod
Normal file
9
2021/7/go.mod
Normal file
|
@ -0,0 +1,9 @@
|
|||
module AoC/2021/7
|
||||
|
||||
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/7/go.sum
Normal file
2
2021/7/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=
|
62
2021/7/main.go
Normal file
62
2021/7/main.go
Normal file
|
@ -0,0 +1,62 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
aoc "AoC/2021/common"
|
||||
"bufio"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func findMinFuel(cf func (distance int) int) func (*bufio.Scanner) int {
|
||||
return func (input *bufio.Scanner) int {
|
||||
max := 0
|
||||
input.Scan()
|
||||
crabs := make(map[int] int)
|
||||
for _, s := range strings.Split(input.Text(), ",") {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if n > max {
|
||||
max = n
|
||||
}
|
||||
|
||||
crabs[n]++
|
||||
}
|
||||
|
||||
// Loop over all possible options
|
||||
costmin := -1
|
||||
for i := 0; i <= max; i++ {
|
||||
cost := 0
|
||||
for p, n := range crabs {
|
||||
distance := p - i
|
||||
if distance < 0 {
|
||||
distance = -distance
|
||||
}
|
||||
|
||||
cost += cf(distance) * n
|
||||
}
|
||||
|
||||
if cost < costmin || costmin == -1 {
|
||||
costmin = cost
|
||||
}
|
||||
}
|
||||
|
||||
return costmin
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
aoc := aoc.New(2021, 7)
|
||||
|
||||
aoc.Test(`16,1,2,0,4,2,7,1,2,14`, []int{37, 168})
|
||||
|
||||
aoc.Solution(1, findMinFuel(func (distance int) int {
|
||||
return distance
|
||||
}))
|
||||
|
||||
aoc.Solution(2, findMinFuel(func (distance int) int {
|
||||
return distance * (distance + 1) / 2
|
||||
}))
|
||||
}
|
Loading…
Reference in New Issue
Block a user