From ff42567b1a96a267702b13f471b5ecde27d81070 Mon Sep 17 00:00:00 2001 From: Sloane Perrault Date: Wed, 21 Sep 2022 09:19:53 -0400 Subject: [PATCH] 2021 day 13 --- 2021/README.md | 3 +- 2021/lib/2021/13.ex | 73 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 2021/lib/2021/13.ex diff --git a/2021/README.md b/2021/README.md index fb040e3..135e9eb 100644 --- a/2021/README.md +++ b/2021/README.md @@ -16,7 +16,7 @@ | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | | | | [1] | [2] | [3] | [4] | | [5] | [6] | [7] | [8] | [9] | [10] | [11]| -| [12]| 13 | 14 | 15 | 16 | 17 | 18 | +| [12]| [13]| 14 | 15 | 16 | 17 | 18 | | 19 | 20 | 21 | 22 | 23 | 24 | 25 | @@ -33,3 +33,4 @@ [10]: ./lib/2021/10.ex [11]: ./lib/2021/11.ex [12]: ./lib/2021/12.ex +[13]: ./lib/2021/13.ex diff --git a/2021/lib/2021/13.ex b/2021/lib/2021/13.ex new file mode 100644 index 0000000..44dd411 --- /dev/null +++ b/2021/lib/2021/13.ex @@ -0,0 +1,73 @@ +import AOC + +aoc 2021, 13 do + def input(input_string \\ input_string()) do + [dots_string, folds_string] = + input_string + |> String.split("\n\n", trim: true) + + dots = + dots_string + |> String.split("\n", trim: true) + |> Enum.map(fn line -> + [x, y] = + String.split(line, ",") + |> Enum.map(&String.to_integer/1) + + {x, y} + end) + |> MapSet.new() + + folds = + folds_string + |> String.split("\n", trim: true) + |> Enum.map(fn + "fold along y=" <> y -> {:y, String.to_integer(y)} + "fold along x=" <> x -> {:x, String.to_integer(x)} + end) + + {dots, folds} + end + + def do_fold({:y, line}, dots) do + for {x, y} <- dots, into: MapSet.new() do + if y > line do + {x, line - (y - line)} + else + {x, y} + end + end + end + + def do_fold({:x, line}, dots) do + for {x, y} <- dots, into: MapSet.new() do + if x > line do + {line - (x - line), y} + else + {x, y} + end + end + end + + def p1 do + {dots, [fold | _folds]} = input() + + do_fold(fold, dots) |> MapSet.size() + end + + def p2 do + {dots, folds} = input() + + final_dots = Enum.reduce(folds, dots, &do_fold/2) + + max_x = final_dots |> Enum.map(&elem(&1, 0)) |> Enum.max() + max_y = final_dots |> Enum.map(&elem(&1, 1)) |> Enum.max() + + for x <- 0..max_x, into: "" do + for y <- 0..max_y, into: "" do + if MapSet.member?(final_dots, {x, y}), do: "#", else: "." + end <> "\n" + end + |> IO.puts() + end +end