Skip to content

Instantly share code, notes, and snippets.

@guregu
Last active December 1, 2022 16:24
Show Gist options
  • Save guregu/a27256f0bcc292ee1a480e0ad5436b2f to your computer and use it in GitHub Desktop.
Save guregu/a27256f0bcc292ee1a480e0ad5436b2f to your computer and use it in GitHub Desktop.
Advent of Code 2022 #1 in Prolog (Trealla Prolog)
% caveat: add an extra line break to the input :-)
:- use_module(library(dcgs)).
:- use_module(library(pio)).
elves([N|Ns]) --> elf(N), elves(Ns).
elves([]) --> [].
elf(Calories) --> sum(Calories), nl.
sum(X) --> number(A), nl, sum(B), { X is A + B }.
sum(0) --> [].
nl --> ['\n'].
% is there a better way to do this? copy-pasted it from another project
number(N) --> { number(N), number_chars(N, D) }, digits(D).
number(N) --> { var(N) }, digits(D), { number_chars(N, D) }.
digits([D|Ds]) --> digit(D), digits_r(Ds).
digits_r([D|Ds]) --> digits([D|Ds]).
digits_r([]) --> [].
digit(D) --> [D], { char_type(D, digit) }.
main :-
once(phrase_from_file(elves(Elves), 'input.txt')),
sort(Elves, Sorted),
reverse(Sorted, [Top1, Top2, Top3|_]),
Sum is Top1 + Top2 + Top3,
format("Top 3: ~w~n", [Sum]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment