Printing string matrix

Q&A's, tips, howto's
Locked
HPW
Posts: 1390
Joined: Thu Sep 26, 2002 9:15 am
Location: Germany
Contact:

Printing string matrix

Post by HPW »

Hello,

I am thinking about a little tool to print all combinations of a string with length 3.
On each pos can be 'A' or 'B' or 'C'.
So I know that it gives 3 * 3 = 27 combinations
AAA
BBB
CCC
...

Anyone an idea to do this lispisch in newLISP?
Generic algo possible with variable length and variable number of possible chars?
Hans-Peter

HPW
Posts: 1390
Joined: Thu Sep 26, 2002 9:15 am
Location: Germany
Contact:

Re: Printing string matrix

Post by HPW »

Got it:

Code: Select all

(dolist (x '("A" "B" "C"))(dolist (y '("A" "B" "C"))(dolist (z '("A" "B" "C"))(println(string x y z)))))
Any better?
Hans-Peter

Patrick
Posts: 7
Joined: Fri May 25, 2012 5:15 pm

Re: Printing string matrix

Post by Patrick »

My candidate:

Code: Select all

(define lst '("A" "B" "C"))

(define (permuations lst i)
    (if (= i 1)
        ;; if i = 1, then just return the list
        lst
        ;; otherwise permutate the list with the permutations of i-1
        (apply append
            (map (fn (x)
                     (map (fn (y) (append x y))
                          lst))
                 (permuations lst (- i 1)))
            2)))

(println (permuations lst 3))

(exit)
Note that mine doesn't just print the items, but generates a list of them, which is probably more useful in most situations.

Locked