39 lines
891 B
Prolog
39 lines
891 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(Commands, X, Y) :-
|
|
step_(Commands, 0, 0, 0, X, Y).
|
|
|
|
step_([], _, X0, Y0, X0, Y0).
|
|
|
|
step_([(forward, N)|Tail], Aim, X0, Y0, X, Y) :-
|
|
X1 is X0 + N,
|
|
Y1 is Y0 + N * Aim,
|
|
step_(Tail, Aim, X1, Y1, X, Y).
|
|
|
|
step_([(up, N)|Tail], Aim, X0, Y0, X, Y) :-
|
|
Aim1 is Aim - N,
|
|
step_(Tail, Aim1, X0, Y0, X, Y).
|
|
|
|
step_([(down, N)|Tail], Aim, X0, Y0, X, Y) :-
|
|
Aim1 is Aim + N,
|
|
step_(Tail, Aim1, X0, Y0, X, Y).
|
|
|