aoc23/18/part1.pl
2023-12-18 00:31:11 -08:00

28 lines
1.0 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(Dir), " ", number(Len), " (#", xdigits(_Color), ")", ("\n"; eos),
{char_code(DirAtom, Dir)}.