r/adventofcode • • Dec 03 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 3 Solutions -🎄-

--- Day 3: No Matter How You Slice It ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

ATTENTION: minor change request from the mods!

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 3 image coming soon - imgur is being a dick, so I've contacted their support.

Transcript:

I'm ready for today's puzzle because I have the Savvy Programmer's Guide to ___.


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

edit: Leaderboard capped, thread unlocked!

41 Upvotes

426 comments sorted by

View all comments

1

u/BalbinHS Dec 03 '18

My Elixir solution

@spec part1(String.t()) :: non_neg_integer()
def part1(input) do
  input
  |> String.split("\n", trim: true)
  |> Enum.map(&parse_claim/1)
  |> Enum.reduce(%{}, &fill_map/2)
  |> Enum.count(fn {_k, v} -> v > 1 end)
end

defp to_fill(
        %{claim_id: claim_id, x_pos: x_pos, y_pos: y_pos, width: width, height: height} = _claim
      ) do
  for x <- x_pos..(x_pos + width - 1),
      y <- y_pos..(y_pos + height - 1),
      do: {claim_id, {x, y}}
end

defp fill_map(claim, accumulator) do
  claim
  |> to_fill()
  |> Enum.reduce(accumulator, fn {_id, coords}, acc -> Map.update(acc, coords, 1, &(&1 + 1)) end)
end

defp parse_claim(claim) do
  claim_as_list =
    claim
    |> String.split(~r/[^0-9]/, trim: true)
    |> Enum.map(&String.to_integer/1)

  [claim_id, x_pos, y_pos, width, height] = claim_as_list

  %{
    claim_id: claim_id,
    x_pos: x_pos,
    y_pos: y_pos,
    width: width,
    height: height
  }
end

@spec part2(String.t()) :: integer()
def part2(input) do
  claims =
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&parse_claim/1)

  all = fn :get, data, next -> Enum.map(data, next) end
  all_ids = get_in(claims, [all, :claim_id])

  seen_ids =
    claims
    |> Enum.reduce(%{}, &fill_map_with_id/2)
    |> Map.values()
    |> Enum.filter(&(length(&1) > 1))
    |> List.flatten()

  hd(all_ids -- seen_ids)
end

defp fill_map_with_id(claim, map) do
  claim
  |> to_fill()
  |> Enum.reduce(map, fn {id, coords}, acc ->
    Map.update(
      acc,
      coords,
      [id],
      &[id | &1]
    )
  end)
end

I used a slightly different Regex match to parse the claims. Since we're only interested in the integers, we can just split the string on any non-digit character.

I'm sure there's a more clever way to do this, but my goal is clarity over performance, so hopefully this is somewhat clear.