diff --git a/2021/7/go.mod b/2021/7/go.mod new file mode 100644 index 0000000..8492a96 --- /dev/null +++ b/2021/7/go.mod @@ -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 diff --git a/2021/7/go.sum b/2021/7/go.sum new file mode 100644 index 0000000..8c9f290 --- /dev/null +++ b/2021/7/go.sum @@ -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= diff --git a/2021/7/main.go b/2021/7/main.go new file mode 100644 index 0000000..16d185c --- /dev/null +++ b/2021/7/main.go @@ -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 + })) +}