r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


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

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

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


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 at 0:10:20!

30 Upvotes

515 comments sorted by

View all comments

1

u/Warbringer007 Dec 05 '18 edited Dec 05 '18

Finally erlang day! Not using ++, it is EXTREMELY slow!

task(File) ->
    In = prepare:readlines(File),
    io:format("~p~n", [firstTask(In, tl(In), [], 0)]),
    io:format("~p~n", [secondTask("qwertzuiolkjhgfdsayxcvbnm", In, 1000000)]).

firstTask([Letter1 | _], [], Acc, 0) -> length([Letter1|Acc]);
firstTask([Letter1 | _], [], Acc, 1) ->
    firstTask([Letter1|Acc], tl([Letter1|Acc]), [], 0);

firstTask([Letter1 | T1], [Letter2 | T2], Acc, If) when ((Letter1 + 32) =/= Letter2) and ((Letter1 - 32) =/= Letter2) ->
    firstTask(T1, T2, [Letter1|Acc], If);

firstTask(_, [_ | T2], Acc, _) ->
    case length(T2) of
        0 -> firstTask(Acc, tl(Acc), [], 0);
        _ -> firstTask(T2, tl(T2), Acc, 1)
    end.

secondTask([], _, Length) -> Length;
secondTask([H|T], In, Length) ->
    FilteredIn = lists:filter( fun(C) -> not lists:member(C, string:lowercase([H])) and not lists:member(C, string:uppercase([H])) end, In ),
    FilteredLength = firstTask(FilteredIn, tl(FilteredIn), [], 0),
    case Length > FilteredLength of
        true -> secondTask(T, In, FilteredLength);
        false -> secondTask(T, In, Length)
    end.

It will reverse order of letters in every pass, but, as I said, ++ is slow, and reverse doesn't matter.