no more char lists in day3

This commit is contained in:
rhiannon morris 2022-12-03 11:24:35 +01:00
parent 3988cfcfc7
commit 6eb6f4bd15

18
day3.m
View file

@ -11,12 +11,17 @@
:- import_module char. :- import_module char.
:- import_module string. :- import_module string.
:- pred split(chars::in, chars::out, chars::out) is semidet. :- pred split(string::in, string::out, string::out) is semidet.
split(X, L, H) :- split(X, L, H) :-
Len = length(X), even(Len), Len = length(X), even(Len),
split_list(Len / 2, X, L, H). split(X, Len / 2, L, H).
:- pred common(list(chars)::in, char::out) is nondet. :- pred member(char::out, string::in) is nondet.
member(C, S) :-
nondet_int_in_range(0, length(S) - 1, I),
index(S, I, C).
:- pred common(list(string)::in, char::out) is nondet.
common([S | Ss], C) :- member(C, S), (Ss = [] ; common(Ss, C)). common([S | Ss], C) :- member(C, S), (Ss = [] ; common(Ss, C)).
:- func prio(char) = int. :- func prio(char) = int.
@ -36,7 +41,7 @@ threes([X, Y, Z | Rest], [t(X, Y, Z) | Groups]) :- threes(Rest, Groups).
:- pred go1(string::in, int::out) is cc_multi. :- pred go1(string::in, int::out) is cc_multi.
go1(Line, Out) :- go1(Line, Out) :-
if split(to_char_list(Line), Fst, Snd), if split(Line, Fst, Snd),
common([Fst, Snd], C) common([Fst, Snd], C)
then then
Out = prio(C) Out = prio(C)
@ -46,11 +51,10 @@ go1(Line, Out) :-
:- pred go2(triple(string)::in, int::out) is cc_multi. :- pred go2(triple(string)::in, int::out) is cc_multi.
go2(t(X, Y, Z), Prio) :- go2(t(X, Y, Z), Prio) :-
if common(map(to_char_list, [X, Y, Z]), C) then if common([X, Y, Z], C) then
Prio = prio(C) Prio = prio(C)
else else
die("no item in common in:\n - %s\n - %s\n - %s", die("no item in common in:\n - %s\n - %s\n - %s", [s(X), s(Y), s(Z)]).
[s(X), s(Y), s(Z)]).
run(one, Lines, univ(sum(Prios))) :- run(one, Lines, univ(sum(Prios))) :-