aoc2021/pl/02.1.pl
2021-12-02 18:50:22 +07:00

35 lines
700 B
Prolog

read_file(Stream, []) :-
at_end_of_stream(Stream).
read_file(Stream, [(Cmd, N)|L]) :-
\+ at_end_of_stream(Stream),
read_line_to_codes(Stream, C),
string_chars(S, C),
split_string(S, " ", "", [S0, S1]),
atom_string(Cmd, S0),
number_string(N, S1),
read_file(Stream, L).
main :-
open('../input/02', read, Stream),
read_file(Stream, Lines), !,
close(Stream),
step(Lines, X, Y),
Z is X * Y,
print((X, Y, Z)).
step([], 0, 0).
step([(forward, N)|Tail], X, Y) :-
step(Tail, X0, Y),
X is X0 + N.
step([(up, N)|Tail], X, Y) :-
step(Tail, X, Y0),
Y is Y0 - N.
step([(down, N)|Tail], X, Y) :-
step(Tail, X, Y0),
Y is Y0 + N.