diff --git a/2021/README.md b/2021/README.md index 4c6bcfc..54008e1 100644 --- a/2021/README.md +++ b/2021/README.md @@ -15,7 +15,7 @@ | S | M | T | W | T | F | S | | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | | | | [1] | [2] | [3] | [4] | -| [5] | [6] | 7 | 8 | 9 | 10 | 11 | +| [5] | [6] | [7] | 8 | 9 | 10 | 11 | | 12 | 13 | 14 | 15 | 16 | 17 | 18 | | 19 | 20 | 21 | 22 | 23 | 24 | 25 | @@ -27,3 +27,4 @@ [4]: ./lib/2021/4.ex [5]: ./lib/2021/5.ex [6]: ./lib/2021/6.ex +[7]: ./lib/2021/7.ex diff --git a/2021/lib/2021/7.ex b/2021/lib/2021/7.ex new file mode 100644 index 0000000..16b986c --- /dev/null +++ b/2021/lib/2021/7.ex @@ -0,0 +1,35 @@ +import AOC + +aoc 2021, 7 do + use AOCHelpers + + def p1 do + crabs = input_number_list() + + max = Enum.max(crabs) + + for position <- 1..max do + for crab <- crabs do + abs(crab - position) + end + |> Enum.sum() + end + |> Enum.min() + end + + def p2 do + crabs = input_number_list() + + max = Enum.max(crabs) + + for position <- 1..max do + for crab <- crabs do + n = abs(crab - position) + 1 / 2 * n * (n + 1) + end + |> Enum.sum() + end + |> Enum.min() + |> trunc() + end +end