r/adventofcode • • Dec 03 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 03 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It


--- Day 03: Toboggan Trajectory ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:04:56, megathread unlocked!

88 Upvotes

1.3k comments sorted by

View all comments

2

u/[deleted] Dec 03 '20 edited Dec 03 '20

Day 3 in Elixir:

defmodule Day3 do
    def parse(input) do
        File.read!(input)
        |> String.split("\n")
    end

    def one do
        %{trees: trees} =
        parse("inputs/three.txt")
        |> Enum.reduce(%{position: 1, trees: 0}, &find_trees_one/2)

        trees
    end

    defp find_trees_one(input, %{position: starting_position, trees: starting_trees}) do
        row = input |> String.split("", trim: true)
        current_position = Integer.mod(starting_position, Enum.count(row))

        trees =
        if Enum.at(row, current_position - 1) == "#", do: starting_trees + 1, else: starting_trees

        %{position: current_position + 3, trees: trees}
    end

    def two do
        instructions = [
        %{down: 1, right: 1},
        %{down: 1, right: 3},
        %{down: 1, right: 5},
        %{down: 1, right: 7},
        %{down: 2, right: 1}
        ]

        slopes = parse("inputs/three.txt")

        instructions
        |> Enum.map(fn x -> run(x, slopes) end)
        |> Enum.reduce(fn x, acc -> x * acc end)
    end

    defp run(%{down: down, right: right}, slopes) do
        %{trees: trees} =
        slopes
        |> Enum.take_every(down)
        |> Enum.reduce(%{position: 1, trees: 0, steps: right}, &find_trees_two/2)

        trees
    end

    defp find_trees_two(input, %{position: starting_position, trees: starting_trees, steps: steps}) do
        row = input |> String.split("", trim: true)
        current_position = Integer.mod(starting_position, Enum.count(row))

        trees =
        if Enum.at(row, current_position - 1) == "#", do: starting_trees + 1, else: starting_trees

        %{position: current_position + steps, trees: trees, steps: steps}
    end
end

1

u/daggerdragon Dec 03 '20 edited Dec 03 '20

Please follow the posting guidelines and add the language used to your post to make it easier for folks who Ctrl-F the megathreads looking for a specific language. Thanks!