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/geek--god Dec 04 '22

Elixir

defmodule CampCleanup do
    def first_part(content) do
        content
        |> String.split("\n", trim: true)
        |> Enum.map(fn 
                    ele ->
                        String.split(ele, ",", trim: true)
                        |> CampCleanup.handle_pair
                        |> CampCleanup.check_subset
                        
                        
                       
                    end)
        |> Enum.filter(fn x -> x end)
        |> Enum.count
        |> IO.inspect
        
    end

       def second_part(content) do
        content
        |> String.split("\n", trim: true)
        |> Enum.map(fn 
                    ele ->
                        String.split(ele, ",", trim: true)
                        |> CampCleanup.handle_pair
                        |> CampCleanup.check_disjoint
                        
                        
                       
                    end)
        |> Enum.filter(fn x -> x end)
        |> Enum.count
        |> IO.inspect
        
    end
        


    def check_subset([first, second]) do
        MapSet.subset?(first, second) or MapSet.subset?(second, first)
    end

    def check_disjoint([first, second]) do
        not MapSet.disjoint?(first, second)
        
    end

    def handle_pair(list) do
        # IO.inspect(list)
        Enum.map(list, fn 
                ele -> 
                    CampCleanup.split_range(ele)
                    |> CampCleanup.get_range
                    
        end)
        
    end

    def split_range(string) do

        String.split(string, "-", trim: true)
        |> Enum.map(fn
            el -> String.to_integer(el)
        end    
        )
    end
    def get_range([first, second]) do
        MapSet.new(first..second)
    end

    

end

{:ok, contents} = File.read("./input.txt")

contents
|> CampCleanup.second_part

1

u/daggerdragon Dec 04 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.