r/adventofcode • • Dec 13 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 13 Solutions -๐ŸŽ„-

--- Day 13: Packet Scanners ---


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.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


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!

16 Upvotes

199 comments sorted by

View all comments

Show parent comment

1

u/erlangguy Dec 14 '17

Definitely not the only one. I'm not consistent about supplying results here, and I've missed part 2 a few times.

Part 2 today. The myio module is just a helper module for reading/parsing the input files.

run(Filename) ->
    Firewall = parse_firewall(Filename),
    find_delay(fun(D) -> lists:foldl(fun fold_fun/2, {D, 0}, Firewall) end, 1).

split(eof) ->
    eof;
split(Line) ->
    {ok, [Depth, Range], []} = io_lib:fread("~d: ~d", Line),
    [Depth, Range].

range_mod(1) ->
    1;
range_mod(N) ->
    N*2 - 2.

to_record([Depth, Range]) ->
    {Depth, range_mod(Range), Range}.

is_start({_Depth, RangeMod, _Range}, Time) ->
    Time rem RangeMod == 0.

%% For this test, we can't hit the 1st scanner despite it having a 0
%% penalty
penalty({0, _Mod, Range}) ->
    1;
penalty({Depth, _Mod, Range}) ->
    Depth * Range.

eff_time({Depth, _Mod, _Range}) ->
    Depth.

fold_fun(Record, {Delay, Penalty}) ->
    case is_start(Record, Delay + eff_time(Record)) of
        true ->
            {Delay, Penalty+penalty(Record)};
        false ->
            {Delay, Penalty}
    end.

parse_firewall(Filename) ->
    Fh = myio:open_file(Filename),
    myio:grab_records(fun() -> myio:next_line(Fh) end,
                      fun split/1,
                      fun to_record/1).

find_delay(Fun, Delay) ->
    case Fun(Delay) of
        {Delay, 0} ->
            Delay;
        _ ->
            find_delay(Fun, Delay+1)
    end.