adamcrussell (adamcrussell) wrote,

2020 Advent Of Code Day 3

Prolog. Developed and tested with SWI-Prolog 8.0.3.

check_and_read(10, [] ,_):-
check_and_read(13, [], _):-
check_and_read(32, [], _):-
check_and_read(end_of_file, [], _):-
check_and_read(Char, [Char|Chars], Stream):-
    get_code(Stream, NextChar),
    check_and_read(NextChar, Chars, Stream).
read_data(Stream, []):-
read_data(Stream, [X|L]):-
    \+ at_end_of_stream(Stream),
    get_code(Stream, Char),
    check_and_read(Char, Chars, Stream),
    atom_codes(X, Chars),
    read_data(Stream, L).

extend(List, Counted, ListExtended):-
    extend(List, Counted, [], ListExtended).
extend(_, 0, ListExtended, ListExtended).
extend(List, Counted, ListExtendedAccum, ListExtended):-
    append(ListExtendedAccum, List, Accum),
    R is Counted - 1,
    extend(List, R, Accum, ListExtended).

advance(Current, Down, Remaining):-
    D is Down - 1,
    advance(Current, D, Remaining, Remaining).
advance(Current, 0, Current, Current).
advance([_|T], Down, _, Remaining):-
    D is Down - 1,
    advance(T, D, T, Remaining).

toboggan(Right, Down, Lines, Positions):-
    toboggan(Right, Down, 0, Lines, [], Positions).
toboggan(_, _, _, [], Positions, Positions).    
toboggan(Right, Down, Index, [H0|T0], PositionsAccum, Positions):-
    advance([H0|T0], Down, [H|T]),
    atom_chars(H, HList),
    length(PositionsAccum, C),
    Counted is C + 1,
    extend(HList, Counted, HListExtended),
    nth0(Index, HListExtended, Position),
    I is Index + Right,
    toboggan(Right, Down, I, T, [Position|PositionsAccum], Positions).
toboggan(Right, Down, Index, _, [_|T], Positions):-
    toboggan(Right, Down, Index, [], T, Positions).
x_count(Positions, Count):-
    x_count(Positions, 0, Count).
x_count([], Count, Count).
x_count([H|T], CountAccum, Count):-
    char_code(H, Code),
    Code == 35,
    C is CountAccum + 1,
    x_count(T, C, Count).
x_count([_|T], CountAccum, Count):-
    x_count(T, CountAccum, Count).
    open('data', read, Stream),
    read_data(Stream, Lines),
    toboggan(1, 1, Lines, Positions_1_1),
    x_count(Positions_1_1, Count1_1),
    format("Count of all Trees: ~d~n", [Count1_1]),
    toboggan(3, 1, Lines, Positions_3_1),
    x_count(Positions_3_1, Count3_1),
    format("Count of all Trees: ~d~n", [Count3_1]),
    toboggan(5, 1, Lines, Positions_5_1),
    x_count(Positions_5_1, Count_5_1),
    format("Count of all Trees: ~d~n", [Count_5_1]),
    toboggan(7, 1, Lines, Positions_7_1),
    x_count(Positions_7_1, Count_7_1),
    format("Count of all Trees: ~d~n", [Count_7_1]),
    toboggan(1, 2, Lines, Positions_1_2),
    x_count(Positions_1_2, Count_1_2),
    format("Count of all Trees: ~d~n", [Count_1_2]),
    Product is Count1_1 * Count3_1 * Count_5_1 *  Count_7_1 * Count_1_2,
    format("Product of all Tree Counts: ~d~n", [Product]).
Tags: advent of code, logic programming, prolog, prolog programming

Recent Posts from This Journal

Comments for this post were disabled by the author