aoc2022/day3.m
2022-12-03 07:03:21 +01:00

62 lines
1.5 KiB
Mathematica

:- module day3.
:- interface.
:- import_module basics.
:- import_module list.
:- import_module univ.
:- pred run(part::in, list(string)::in, univ::out) is cc_multi.
:- implementation.
:- import_module int.
:- import_module char.
:- import_module string.
:- pred split(chars::in, chars::out, chars::out) is semidet.
split(X, L, H) :-
Len = length(X), even(Len),
split_list(Len / 2, X, L, H).
:- pred common(list(chars)::in, char::out) is nondet.
common([S | Ss], C) :- member(C, S), (Ss = [] ; common(Ss, C)).
:- func prio(char) = int.
prio(C) = I :-
if is_lower(C) then
I = to_int(C) - to_int('a') + 1
else
I = to_int(C) - to_int('A') + 27.
:- type triple(T) ---> t(T, T, T).
:- pred threes(list(T)::in, list(triple(T))::out) is semidet.
threes([], []).
threes([X, Y, Z | Rest], [t(X, Y, Z) | Groups]) :- threes(Rest, Groups).
:- pred go1(string::in, int::out) is cc_multi.
go1(Line, Out) :-
if split(to_char_list(Line), Fst, Snd),
common([Fst, Snd], C)
then
Out = prio(C)
else
die("invalid line: ""%s""", [s(Line)]).
:- pred go2(triple(string)::in, int::out) is cc_multi.
go2(t(X, Y, Z), Prio) :-
if common(map(to_char_list, [X, Y, Z]), C) then
Prio = prio(C)
else
die("no item in common in:\n - %s\n - %s\n - %s",
[s(X), s(Y), s(Z)]).
run(one, Lines, univ(sum(Prios))) :-
map(go1, Lines, Prios).
run(two, Lines, univ(sum(Prios))) :-
if threes(Lines, Groups) then
map(go2, Groups, Prios)
else
die("not a multiple of three lines").