DEV Community

Caleb Weeks
Caleb Weeks

Posted on • Originally published at sethcalebweeks.com

2 1

Advent of Code Day 6

Links

Highlights

  • 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
    input
    |> 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}
      end
    end)
    |> elem(0)
  end

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

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

end
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay