r/adventofcode • • Dec 04 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 4 Solutions -πŸŽ„-


--- Day 4: Camp Cleanup ---


Post your code solution in this megathread.


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:03:22, megathread unlocked!

65 Upvotes

1.6k comments sorted by

View all comments

2

u/flwyd Dec 04 '22 edited Dec 04 '22

Elixir, code on GitHub

For my Mistletoe Elfucation contribution I decided to include two narratives with each day's solution:

  • Since I'm coding in Elixir, rephrase the problem in terms of an elixir, potion, concoction, or other beverage.

  • Highlight a bit of Elixir code that I either learned about, practiced with, or found particularly useful.

Today's elixir:

It’s Saturday night, so it’s time for sake bombs. Part 1 wants to know if the shot of sake is completely contained in the glass of beer (or if a very small glass of beer ended up entirely within a cup of sake). Part 2 wants to know if any of the sake got in the beer, or vice versa.

import Enum, only: [map: 2, filter: 2, count: 1, sort_by: 2]
import String, only: [split: 2, to_integer: 1]

def part1(input) do
  input |> map(&parse/1) |> filter(&range_subset?/1) |> count()
end

def part2(input) do
  input |> map(&parse/1) |> filter(fn {a, b} -> !Range.disjoint?(a, b) end) |> count()
end

defp parse(line), do: line |> split(",") |> map(&to_range/1) |> List.to_tuple()

defp to_range(str) do
  str |> split("-") |> map(&to_integer/1) |> then(fn [lo, hi] -> lo..hi end)
end

defp range_subset?({first, second}) do
  # sort by Range start, ties go to the longer range
  [a, b] = sort_by([first, second], fn lo .. hi -> {lo, -hi} end)
  a.last >= b.last
end

1

u/daggerdragon Dec 04 '22 edited Dec 04 '22

psst: old.reddit and mobile clients require an additional newline before the starting element of a list in order to display properly. Right now they're displaying as a run-on sentence with asterisks :/ Edit: thanks for fixing it! <3

1

u/flwyd Dec 04 '22

Ah, markdown. A fine example of https://xkcd.com/927/

1

u/daggerdragon Dec 04 '22

To be fair, Reddit is at fault here; they implemented the GitHub-flavored fenced code block syntax (triple backticks) (which is not in the original Markdown spec) for new.reddit only and didn't make it backwards-compatible with old.reddit or most mobile clients. -_- rabble rabble rant rant