aoc23/18/part2.pl
2023-12-18 00:40:31 -08:00

32 lines
1.1 KiB
Prolog

:- use_module(library(pio)).
:- use_module(library(dcg/basics)).
:- initialization(main, main).
main([FileName|_]) :-
input(FileName, Moves),
area(Moves, Area),
write(Area), nl.
area(Moves, Area) :-
area(Moves, 0, A1), MainArea is abs(A1),
convlist([r-N, N]>>(true), Moves, Horzs), sum_list(Horzs, Horz),
convlist([u-N, N]>>(true), Moves, Verts), sum_list(Verts, Vert),
Area is MainArea + Horz + Vert + 1.
area([], _, 0).
area([u-Len|Moves], H, Area) :- NewH is H + Len, area(Moves, NewH, Area).
area([d-Len|Moves], H, Area) :- NewH is H - Len, area(Moves, NewH, Area).
area([r-Len|Moves], H, Area) :- area(Moves, H, Area2), Area is Area2 + H*Len.
area([l-Len|Moves], H, Area) :- area(Moves, H, Area2), Area is Area2 - H*Len.
input(FileName, Moves) :- phrase_from_file(moves(Moves), FileName).
moves([]) --> eos, !.
moves([Move|Moves]) --> move(Move), moves(Moves).
move(DirAtom-Len) -->
alpha_to_lower(_), " ", number(_), " (#", xinteger(Hex), ")", ("\n"; eos),
{DirNum is Hex /\ 15, dir(DirNum, DirAtom), Len is Hex >> 4}.
dir(0, r).
dir(1, d).
dir(2, l).
dir(3, u).