Sujet : Re: Given string 'a.bc.' -- replace each dot(.) with 0 or 1
De : markw (at) *nospam* distorted.org.uk (Mark Wooding)
Groupes : comp.lang.lispDate : 24. May 2024, 18:27:28
Autres entêtes
Message-ID : <864jandvkf.fsf.markw@stratocaster.distorted.org.uk>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux)
HenHanna <
HenHanna@devnull.tb> writes:
How can i write this function simply? (in Common Lisp)
>
-- Given a string 'a.bc.' -- replace each dot(.) with 0 or 1.
>
-- So the value is a list of 4 strings:
('a0bc0' 'a0bc1' 'a1bc0' 'a1bc1')
>
-- The order is not important.
If the string has 3 dots, the value is a list of length 8.
Oh, all right. I'll bite.
(defun replace-dots (string &key (start 0) end)
(unless end (setf end (length string)))
(let ((dots (make-array 16
:element-type 'fixnum
:adjustable t
:fill-pointer 0))
(string (copy-seq string)))
(do ((pos (position #\. string :start start :end end)
(position #\. string :start (1+ pos) :end end)))
((null pos))
(vector-push-extend pos dots))
(let* ((ndots (length dots))
(niter (ash 1 ndots))
(list nil))
(dotimes (i ndots)
(setf (char string (aref dots i)) #\0))
(push (copy-seq string) list)
(do ((i 1 (1+ i)))
((>= i niter))
(let* ((k (1- (integer-length (logand i (- i)))))
(dot (aref dots k)))
(setf (char string dot)
(code-char (logxor (char-code (char string dot))
#.(logxor (char-code #\0)
(char-code #\1)))))
(push (copy-seq string) list)))
list)))
Now that I look again, I see that you asked for `simple'. I fail at
that. But it's nonrecursive, and, perhaps, an interesting approach.
-- [mdw]