Last active
December 1, 2022 16:24
-
-
Save guregu/a27256f0bcc292ee1a480e0ad5436b2f to your computer and use it in GitHub Desktop.
Advent of Code 2022 #1 in Prolog (Trealla Prolog)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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