-
Notifications
You must be signed in to change notification settings - Fork 0
/
p13.pl
23 lines (18 loc) · 959 Bytes
/
p13.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
% P13 (**): Run-length encoding of a list (direct solution)
% encode_direct(L1,L2) :- the list L2 is obtained from the list L1 by
% run-length encoding. Consecutive duplicates of elements are encoded
% as terms [N,E], where N is the number of duplicates of the element E.
% However, if N equals 1 then the element is simply copied into the
% output list.
% (list,list) (+,?)
encode_direct([],[]).
encode_direct([X|Xs],[Z|Zs]) :- count(X,Xs,Ys,1,Z), encode_direct(Ys,Zs).
% count(X,Xs,Ys,K,T) Ys is the list that remains from the list Xs
% when all leading copies of X are removed. T is the term [N,X],
% where N is K plus the number of X's that can be removed from Xs.
% In the case of N=1, T is X, instead of the term [1,X].
count(X,[],[],1,X).
count(X,[],[],N,[N,X]) :- N > 1.
count(X,[Y|Ys],[Y|Ys],1,X) :- X \= Y.
count(X,[Y|Ys],[Y|Ys],N,[N,X]) :- N > 1, X \= Y.
count(X,[X|Xs],Ys,K,T) :- K1 is K + 1, count(X,Xs,Ys,K1,T).