Page 1 of 1

Generating lists of given length

Posted: Mon Sep 26, 2011 4:16 pm
by lprog
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".

Re: Generating lists of given length

Posted: Mon Sep 26, 2011 5:47 pm
by gugamilare
Can you at least show us an attempt to solve the problem?

Re: Generating lists of given length

Posted: Wed Oct 19, 2011 12:17 pm
by lprog
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:

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))))

I want to send the output of function gen to a file.How can i do that?

Re: Generating lists of given length

Posted: Fri Oct 28, 2011 3:56 pm
by virex
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.