Printing string matrix

Started by HPW, May 31, 2012, 07:15:12 AM

Previous topic - Next topic

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

#1
Got it:

(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

#2
My candidate:


(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.