diff --git a/day7.pl b/day7.pl index 8420917..347824d 100644 --- a/day7.pl +++ b/day7.pl @@ -29,7 +29,8 @@ rank(five, 6). hand_rank(C, R) :- hand(C, H), rank(H, R). -compare_rank(X, C1, C2) :- hand_rank(C1, R1), hand_rank(C2, R2), compare(X, R1, R2). +compare_rank(X, C1, C2) :- + hand_rank(C1, R1), hand_rank(C2, R2), compare(X, R1, R2). compare_hand(X, C1-_, C2-_) :- compare_rank(X0, C1, C2), @@ -39,19 +40,17 @@ compare_hand(X, C1-_, C2-_) :- total(Xs, R) :- total(1, Xs, R). total(_, [], 0). -total(I, [_-X|Xs], R) :- - I1 is I + 1, - total(I1, Xs, R0), - R is R0 + (I * X). +total(I, [_-X|Xs], R) :- I1 is I + 1, total(I1, Xs, R0), R is R0 + (I * X). :- use_module(library(dcg/basics)). -card(V) --> [X], {char_code(C, X), value(C, V)}. -cards(Cs) --> card(A), card(B), card(C), card(D), card(E), {Cs = [A,B,C,D,E]}. -bid(N) --> digits(Ds), {number_chars(N, Ds)}. -spaces --> " ", (spaces ; []). -line(Cs-B) --> cards(Cs), spaces, bid(B). +card(V) --> [X], {char_code(C, X), value(C, V)}. +cards(Cs) --> card(A), card(B), card(C), card(D), card(E), {Cs = [A,B,C,D,E]}. +bid(N) --> digits(Ds), {number_chars(N, Ds)}. +spaces --> " ", (spaces ; []). +line(Cs-B) --> cards(Cs), spaces, bid(B). + lines([]) --> "\n" ; []. lines([L|Ls]) --> line(L), "\n", lines(Ls). @@ -60,7 +59,7 @@ value('J', 11). value('Q', 12). value('K', 13). value('A', 14). -value(C, N) :- char_code(C, N0), N is N0 - 0x30, N >= 0, N =< 9. +value(C, N) :- number_chars(N, [C]). part1(File) :- @@ -70,9 +69,9 @@ part1(File) :- writeln(R), !. +part1_to_part2(Xs-B, Ys-B) :- maplist(joker, Xs, Ys). joker(11, 0). joker(X, X) :- X \= 11. -part1_to_part2(Xs-B, Ys-B) :- maplist(joker, Xs, Ys). part2(File) :- phrase_from_file(lines(Ls0), File),