d23p2 naive

This commit is contained in:
Dory 2023-12-24 23:40:09 -08:00
parent e0a1757e9e
commit 69e2bc3b20

51
23/part2.pl Normal file
View File

@ -0,0 +1,51 @@
:- use_module(library(pio)).
:- use_module(library(dcg/basics)).
:- initialization(main, main).
:- table neighbor/3.
main([FileName|_]) :-
input(FileName, Map),
nth1(1, Map, Row1), nth1(StartY, Row1, '.'),
findall(
N,
(route(Map, visited{}, 1-StartY, N), format('~w, ', [N]), flush_output),
Ns),
max_list(Ns, Answer),
nl, format('Answer = ~w', [Answer]), nl.
route(Map, _, X-_, 0) :- length(Map, Height), X =:= Height.
route(Map, Visiteds, X-Y, N) :-
Key is X*1000 + Y, NextVisiteds = Visiteds.put(Key, true),
neighbor(Map, X-Y, X1-Y1),
NeighborKey is X1*1000 + Y1, \+ _= Visiteds.get(NeighborKey),
route(Map, NextVisiteds, X1-Y1, N1),
N is N1 + 1.
neighbor(Map, X-Y, X1-Y1) :-
( X1 is X + 1, Y1 = Y;
X1 is X - 1, Y1 = Y;
X1 = X, Y1 is Y + 1;
X1 = X, Y1 is Y - 1
),
nth1(X1, Map, Row1), nth1(Y1, Row1, '.').
% input parsing stuff below. Brick indexing is for debugging.
input(FileName, Map) :- phrase_from_file(lines(Map), FileName).
lines([]) --> eos, !.
lines([Line|Lines]) --> line(Line), lines(Lines).
line([]) --> ("\n"; eos), !.
line(['#'|Chars]) --> "#", line(Chars).
line(['.'|Chars]) --> ("."; ">"; "v"), line(Chars).
% debug
print(Map) :-
findall(
X,
( nth1(X, Map, Line),
format('~3d', [X]), write(" "),
atomic_list_concat(Line, Str), write(Str), nl
),
_),
nl.