aoc2021/pl/03.1.pl

64 lines
1.3 KiB
Perl
Raw Normal View History

2021-12-09 01:41:52 +07:00
chars_digits([], []).
chars_digits([C|Cs], [D|Ds]) :-
char_type(C, digit(D)),
chars_digits(Cs, Ds).
read_file(Stream, []) :-
at_end_of_stream(Stream).
read_file(Stream, [X|L]) :-
\+ at_end_of_stream(Stream),
read_line_to_codes(Stream, C),
chars_digits(C, X),
read_file(Stream, L).
main :-
open('../input/03', read, Stream),
read_file(Stream, Lines), !,
close(Stream),
solve(Lines, A, B),
bin_dec(A, A1),
bin_dec(B, B1),
X is A1 * B1,
print([A1, B1, X]).
list_sum([], [], []).
list_sum([A|As], [B|Bs], [C|Cs]) :-
list_sum(As, Bs, Cs),
C is A + B.
listlist_sum([], C, C).
listlist_sum([A|As], I, C) :-
list_sum(A, I, I1),
listlist_sum(As, I1, C).
zerolist([], []).
zerolist([_|As], [0|Bs]) :-
zerolist(As, Bs).
listlist_sum([A|As], Sum) :-
zerolist(A, B),
listlist_sum([A|As], B, Sum).
div([], _, []).
div([A|As], N, [B|Bs]) :-
B is A // N,
div(As, N, Bs).
neg([], []).
neg([A|As], [B|Bs]) :-
B is 1 - A,
neg(As, Bs).
solve(Lines, Res1, Res2) :-
listlist_sum(Lines, Sum),
length(Lines, Len),
div(Sum, Len // 2, Res1),
neg(Res1, Res2).
bin_dec(B, X) :-
bin_dec(B, 0, X).
bin_dec([], X, X).
bin_dec([B|Bs], N, X) :-
M is N * 2 + B,
bin_dec(Bs, M, X).