Day 1

2020-01-21

Problem

This first problem took me far longer than I would have liked. I had to figure out how to parse the data to event start asking my questions. The append/3 solution was not my first choice, but I couldn’t figure out why my original answer was short circuiting. Once I figured it out, it was super easy to solve the second part of the question.

I had an ugly solution that relied on permutation/2 by only looking at the first two elements of the list and relying on backtracking. While this worked for the sample input, it ended up being far too large for it to be tractable on the actual question input. The idea that you can just declare things and have backtracking solve everything to you is not free — it still requires understanding the mechanism behind how Prolog searches for answers.

Solution

cast_int([X], [Y]) :- atom_number(X, Y).
cast_int([X|XS], [Y|YS]):-
    atom_number(X, Y),
    cast_int(XS, YS).

main(Input, Answer):-
    split_string(Input, "\n", "\n", L),
    cast_int(L, Casted),
    append([_, [X], _, [Y], _], Casted),
    2020 is X+Y,
    Answer is X*Y.

main2(Input, Answer):-
    split_string(Input, "\n", "\n", L),
    cast_int(L, Casted),
    append([_,[X],_,[Y],_,[Z],_], Casted),
    2020 is X+Y+Z,
    Answer is X*Y*Z.

sample(X):-
    X = "1721
979
366
299
675
1456".

Index