%Source: https://sites.google.com/site/prologsite/prolog-problems %query:encode_modified(g,f). % 1.11 (*): Modified run-length encoding % encode_modified(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_modified(L1,L2) :- encode(L1,L), strip(L,L2). strip([],[]). strip([[1,X]|Ys],[X|Zs]) :- strip(Ys,Zs). strip([[N,X]|Ys],[[N,X]|Zs]) :- N > 1, strip(Ys,Zs). encode(L1,L2) :- pack(L1,L), transform(L,L2). transform([],[]). transform([[X|Xs]|Ys],[[N,X]|Zs]) :- length([X|Xs],N), transform(Ys,Zs). pack([],[]). pack([X|Xs],[Z|Zs]) :- transfer(X,Xs,Ys,Z), pack(Ys,Zs). % transfer(X,Xs,Ys,Z) Ys is the list that remains from the list Xs % when all leading copies of X are removed and transfered to Z transfer(X,[],[],[X]). transfer(X,[Y|Ys],[Y|Ys],[X]) :- X \= Y. transfer(X,[X|Xs],Ys,[X|Zs]) :- transfer(X,Xs,Ys,Zs).