day 2 (prolog)
This commit is contained in:
parent
2309d64e77
commit
531a880e0f
34
pl/02.1.pl
Normal file
34
pl/02.1.pl
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
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.
|
||||||
|
|
38
pl/02.2.pl
Normal file
38
pl/02.2.pl
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
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).
|
||||||
|
|
Loading…
Reference in a new issue