* Storing strings in a list when some condition is true
@ 2023-07-29 17:40 Heime
0 siblings, 0 replies; only message in thread
From: Heime @ 2023-07-29 17:40 UTC (permalink / raw)
To: Heime via Users list for the GNU Emacs text editor
I am using this function to generate permutations of characters in a string.
The algorithm uses recursion, but the final string that is needed is the one
at which the condition (= i length) holds true (currently I just call message).
Suppose one starts with (permute "word" 0 4), different strings are generated
but the ones I need saved are the ones for which (= i length) is satisfied.
How can put all the words generated in a list ?
(defun permute (string i length)
"Generate permutations of STRING."
(if (= i length)
(message "%s" string)
(let ( (j i) )
(while (< j length)
(swap-chars string i j)
(permute string (1+ i) length)
(swap-chars string i j)
(setq j (1+ j))) )))
where swap-chars is
(defun swap-chars (string p q)
"Swap chars in STRING at positions P and Q.
This is a destructive operation."
(aset string p (prog1 (aref string q)
(aset string q (aref string p))))
string)
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2023-07-29 17:40 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-07-29 17:40 Storing strings in a list when some condition is true Heime
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).