DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 2: Password Philosophy

Collapse
 
patryk profile image
Patryk Woziński • Edited

Hi guys!
The second day was awesome. I've really enjoyed the task. :) I'm still learning Elixir, but I think my solution was not that bad. :) Of course, I did it in Elixir.

This time I've split the day into two modules - one per part. The full solution is on my GitHub repository.

The first part of the day looks like:

defmodule AdventOfCode.Day2Part1 do
  @pattern ~r/(?<min>\d*)-(?<max>\d*)\s(?<char>\w):\s*(?<password>\w*)/

  def calculate(file_path) do
    file_path
    |> File.stream!()
    |> Stream.map(&String.replace(&1, "\n", ""))
    |> Stream.map(fn line ->
      Regex.named_captures(@pattern, line)
    end)
    |> Stream.filter(fn %{"char" => char, "min" => min, "max" => max, "password" => password} ->
      occurrences =
        password
        |> String.graphemes()
        |> Enum.count(&(&1 == char))

      occurrences >= String.to_integer(min) and occurrences <= String.to_integer(max)
    end)
    |> Enum.count()
  end
end
Enter fullscreen mode Exit fullscreen mode

The second part of the day looks like:

defmodule AdventOfCode.Day2Part2 do
  @pattern ~r/(?<x>\d*)-(?<y>\d*)\s(?<char>\w):\s*(?<password>\w*)/

  def calculate(file_path) do
    file_path
    |> File.stream!()
    |> Stream.map(&String.replace(&1, "\n", ""))
    |> Stream.map(fn line ->
      Regex.named_captures(@pattern, line)
    end)
    |> Stream.filter(fn %{"char" => char, "x" => x, "y" => y, "password" => password} ->
      at_position?(char, x, password) != at_position?(char, y, password)
    end)
    |> Enum.count()
  end

  defp at_position?(char, position, password) do
    String.at(password, String.to_integer(position) - 1) == char
  end
end
Enter fullscreen mode Exit fullscreen mode