Generating lists of given length

Discussion of Common Lisp

Generating lists of given length

Postby 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".
lprog
 
Posts: 2
Joined: Mon Sep 26, 2011 4:04 pm

Re: Generating lists of given length

Postby gugamilare » Mon Sep 26, 2011 5:47 pm

Can you at least show us an attempt to solve the problem?
gugamilare
 
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil

Re: Generating lists of given length

Postby 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?
lprog
 
Posts: 2
Joined: Mon Sep 26, 2011 4:04 pm

Re: Generating lists of given length

Postby 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.
virex
 
Posts: 17
Joined: Fri Oct 28, 2011 3:41 pm


Return to Common Lisp

Who is online

Users browsing this forum: Bing [Bot] and 2 guests

cron