adamcrussell (adamcrussell) wrote,
adamcrussell
adamcrussell

2020 Advent of Code Day 1

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, []):-
    at_end_of_stream(Stream).
read_data(Stream, [X|L]):-
    \+ at_end_of_stream(Stream),
    get_code(Stream, Char),
    check_and_read(Char, Chars, Stream),
    number_codes(X, Chars),
    read_data(Stream, L).
    
pair_sum_to_2020(Numbers, Pair):-
    pair_sum_to_2020(Numbers, Numbers, Numbers, Pair).
pair_sum_to_2020([], _, _, _).   
pair_sum_to_2020([], [], _, _).
pair_sum_to_2020([_|TI], [], Numbers, Pair):-   
    pair_sum_to_2020(TI, Numbers, Numbers, Pair).
pair_sum_to_2020([HI|_], [HJ|_], Numbers, Pair):-
    Sum is HI + HJ,
    Sum == 2020,
    Pair = [HI, HJ],
    pair_sum_to_2020([], [], Numbers, Pair).
pair_sum_to_2020([HI|TI], [_|TJ], Numbers, Pair):-
    pair_sum_to_2020([HI|TI], TJ, Numbers, Pair).

triple_sum_to_2020(Numbers, Triple):-
    triple_sum_to_2020(Numbers, Numbers, Numbers, Triple).
triple_sum_to_2020([], _, _, _).   
triple_sum_to_2020([], [], _, _).
triple_sum_to_2020([_|TI], [], Numbers, Triple):-   
    triple_sum_to_2020(TI, Numbers, Numbers, Triple).
triple_sum_to_2020([HI|_], [HJ|_], Numbers, Triple):-
    Delta is 2020 - HI - HJ,
    member(Delta, Numbers),
    Triple = [HI, HJ, Delta],
    triple_sum_to_2020([], [], Numbers, Triple).
triple_sum_to_2020([HI|TI], [_|TJ], Numbers, Triple):-
    triple_sum_to_2020([HI|TI], TJ, Numbers, Triple).
    
write_pair_product([P0, P1]):-
    Product is P0 * P1,
    format("Product of ~d and ~d is ~d~n",[P0, P1, Product]).

write_triple_product([T0, T1, T2]):-
    Product is T0 * T1 * T2,
    format("Product of ~d and ~d and ~d is ~d~n", [T0, T1, T2, Product]).
    
main:-
    open('data', read, Stream),
    read_data(Stream, Numbers),
    close(Stream),
    pair_sum_to_2020(Numbers, Pair),
    write_pair_product(Pair),
    triple_sum_to_2020(Numbers, Triple),
    write_triple_product(Triple),
    halt.
Tags: advent of code, logic programming, prolog, prolog programming
Subscribe

Recent Posts from This Journal

Comments for this post were disabled by the author