help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: List not getting filled up


From: uzibalqa
Subject: Re: List not getting filled up
Date: Sun, 30 Jul 2023 14:47:08 +0000

------- Original Message -------
On Monday, July 31st, 2023 at 2:28 AM, tpeplt <tpeplt@gmail.com> wrote:

> uzibalqa uzibalqa@proton.me writes:

> 1. Provide a specification of the problem that you want your
> procedure to solve. For example, provide calls to your
> procedure with a range of values and the results that you want
> your procedure to produce:

Use this as a test

(setq collection '())
(permute "abc" 0 3 collection) 
(message "%s" collection)

I should get

collection (abc acb bac bca cba cab)

But I get

Collection (abc abc abc abc abc abc)

Here is the function permute

(defun permute (string i length &optional result)
  "Generate permutations of STRING using Backtracking Algorithm."

  (if (null result) (setq result '()))

  (if (= i length)
      
      (progn (message "%s" string)
             (push string result))

    (let ( (j i) )
      (while (< j length)
        (swap-chars string i j)
        ;; Update result through recursion
        (setq result (permute string (1+ i) length result))
        (swap-chars string i j)
        (setq j (1+ j))) ))

  result)

Here is the supporting function swap-chars

(defun swap-chars (string p q)
  "Swap chars in STRING at positions P and Q.
This is a destructive operation."

  (aset string p                         ; Store char d at index p
    (prog1 (aref string q)               ; Save character d
      (aset string q (aref string p))))  ; Store char b at index q

  string)






reply via email to

[Prev in Thread] Current Thread [Next in Thread]