day 7 prolog
This commit is contained in:
parent
b69b03fc31
commit
5b5f21ce4a
28
pl/07.1.pl
Normal file
28
pl/07.1.pl
Normal file
|
@ -0,0 +1,28 @@
|
|||
numbers_strings([], []).
|
||||
numbers_strings([A|As], [B|Bs]) :-
|
||||
number_string(A, B),
|
||||
numbers_strings(As, Bs).
|
||||
|
||||
read_file(Stream, X) :-
|
||||
\+ at_end_of_stream(Stream),
|
||||
read_line_to_codes(Stream, C),
|
||||
string_chars(S, C),
|
||||
split_string(S, ",", "", Y),
|
||||
numbers_strings(X, Y),
|
||||
at_end_of_stream(Stream).
|
||||
|
||||
main :-
|
||||
open('../input/07', read, Stream),
|
||||
read_file(Stream, Lines), !,
|
||||
close(Stream),
|
||||
msort(Lines, L),
|
||||
length(L, Len),
|
||||
I is Len // 2,
|
||||
nth0(I, L, X),
|
||||
calculate_diff(L, X, N),
|
||||
print([X, N]).
|
||||
|
||||
calculate_diff([], _, 0).
|
||||
calculate_diff([A|As], X, B) :-
|
||||
calculate_diff(As, X, B0),
|
||||
B is B0 + abs(A - X).
|
41
pl/07.2.pl
Normal file
41
pl/07.2.pl
Normal file
|
@ -0,0 +1,41 @@
|
|||
numbers_strings([], []).
|
||||
numbers_strings([A|As], [B|Bs]) :-
|
||||
number_string(A, B),
|
||||
numbers_strings(As, Bs).
|
||||
|
||||
read_file(Stream, X) :-
|
||||
\+ at_end_of_stream(Stream),
|
||||
read_line_to_codes(Stream, C),
|
||||
string_chars(S, C),
|
||||
split_string(S, ",", "", Y),
|
||||
numbers_strings(X, Y),
|
||||
at_end_of_stream(Stream).
|
||||
|
||||
main :-
|
||||
open('../input/07', read, Stream),
|
||||
read_file(Stream, Lines), !,
|
||||
close(Stream),
|
||||
msort(Lines, L),
|
||||
min_list(L, A),
|
||||
max_list(L, B),
|
||||
bin_search(A, B, L, N),
|
||||
print(N).
|
||||
|
||||
tri(A, B) :-
|
||||
B is (A * (A + 1)) // 2.
|
||||
|
||||
calculate_diff([], _, 0).
|
||||
calculate_diff([A|As], X, B) :-
|
||||
calculate_diff(As, X, B0),
|
||||
tri(abs(A - X), T),
|
||||
B is B0 + T.
|
||||
|
||||
bin_search(L, L, A, Ans) :-
|
||||
calculate_diff(A, L, Ans).
|
||||
bin_search(L, R, A, Ans) :-
|
||||
L < R,
|
||||
M is (L + R) // 2,
|
||||
((M >= R, A1 is 9999999999999999); bin_search(L, M, A, A1)),
|
||||
((M =< L, A2 is 9999999999999999); bin_search(M, R, A, A2)),
|
||||
Ans is min(A1, A2).
|
||||
|
Loading…
Reference in a new issue