Generating lists of given length

Discussion of Common Lisp
Post Reply
lprog
Posts: 2
Joined: Mon Sep 26, 2011 4:04 pm

Generating lists of given length

Post by lprog » Mon Sep 26, 2011 4:16 pm

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

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

Re: Generating lists of given length

Post by gugamilare » Mon Sep 26, 2011 5:47 pm

Can you at least show us an attempt to solve the problem?

lprog
Posts: 2
Joined: Mon Sep 26, 2011 4:04 pm

Re: Generating lists of given length

Post by lprog » Wed Oct 19, 2011 12:17 pm

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?

virex
Posts: 17
Joined: Fri Oct 28, 2011 3:41 pm

Re: Generating lists of given length

Post by virex » Fri Oct 28, 2011 3:56 pm

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.

Post Reply