DEV Community

Caleb Weeks
Caleb Weeks

Posted on • Originally published at

Advent of Code Day 6



  • This may have been the simplest problem so far. For a while, I was checking the wrong stopping condition, so it took me longer than it should have.
  • Reduce is my go-to construct for processing a list of things. You can cram as many things into the accumulator as you need to. There are probably other enumerable operations that would do a better job, but reduce is the one-size-fits-all tool that I always reach for.
defmodule Day06 do
  use AOC

  def first_marker(input, marker_length) do
    |> String.to_charlist
    |> Enum.reduce({0, [], false}, fn char, {count, window, stop} ->
      cond do
        stop -> {count, window, true}
        length(window) < marker_length -> {count + 1, window ++ [char], false}
        length(Enum.uniq(window)) == marker_length -> {count, window, true}
        true -> {count + 1, Enum.slice(window, 1, marker_length - 1) ++ [char], false}
    |> elem(0)

  def part1, do: input(6) |> first_marker(4)

  def part2, do: input(6) |> first_marker(14)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)