August 19, 2024
P10 - Run-length encoding of a list
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.
Example:* (encode '(a a a a b c c a a d e e e e))((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))
lisp
(defun encode (l &optional (n 1))
(cond
((null l) nil)
((null (cdr l)) (list (list (car l) n)))
((eql (car l) (cadr l)) (encode (cdr l) (1+ n)))
(t (cons (list (car l) n) (encode (cdr l) 1)))))