Generating lists of given length
Generating lists of given length
Hello.How can I generate all possible lists of length n,consisting of elements "a" and "b".For example,if n=5 there must be 32 lists of length 5,consisting of "a" and "b".
-
- Posts: 406
- Joined: Sat Mar 07, 2009 6:17 pm
- Location: Brazil
- Contact:
Re: Generating lists of given length
Can you at least show us an attempt to solve the problem?
Re: Generating lists of given length
I've written some code that generates lists of given length and consisting of 2 types of elements. The result is a list that consists of lists representing the chains of elements. When n=1,the result is ((a) (b)),when n=2 the result is ((a a)(b a)(a b)(b b)).Here is my code:
I want to send the output of function gen to a file.How can i do that?
Code: Select all
(defun ota(c d)(if (null c) (list d)
(if (=(list-length c)1)(list (append (car c)(list (car d))))
(cons (append (car c) (list (car d)))
(ota (cdr c) d)) )))
(defun m(c d) (if (=(list-length d)1)(ota c d)
(append (m c (list (car d))) (m c (cdr d)))))
(defun gen(a n) (if(= n 0) nil (if(= n 1)(list (list (car a)) (cdr a) )
(m (gen a (1- n))a))))
Re: Generating lists of given length
You can use the with-open-file macro in conjunction with either format or write. Take a look here for an explanation on reading from and writing to files.