Page 1 of 1

Printing string matrix

Posted: Thu May 31, 2012 2:15 pm
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?

Re: Printing string matrix

Posted: Thu May 31, 2012 2:28 pm
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?

Re: Printing string matrix

Posted: Thu May 31, 2012 5:37 pm
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.