Generate Permutations of a List

Posted by Eric Mercer on Stack Overflow See other posts from Stack Overflow or by Eric Mercer
Published on 2012-02-16T06:10:56Z Indexed on 2012/09/15 9:38 UTC
Read the original article Hit count: 188

Filed under:
|
|

I'm writing a function that takes a list and returns a list of permutations of the argument.

I know how to do it by using a function that removes an element and then recursively use that function to generate all permutations. I now have a problem where I want to use the following function:

(define (insert-everywhere item lst)
  (define (helper item L1 L2)
    (if (null? L2) (cons (append L1 (cons item '())) '())
        (cons (append L1 (cons item L2)) 
              (helper item (append L1 (cons (car L2) '())) (cdr L2)))))
  (helper item '() lst))

This function will insert the item into every possible location of the list, like the following:

(insert-everywhere 1 '(a b)) 

will get:

'((1 a b) (a 1 b) (a b 1))

How would I use this function to get all permutations of a list?

I now have:

(define (permutations lst)
  (if (null? lst) 
      '()
      (insert-helper (car lst) (permutations (cdr lst)))))

(define (insert-helper item lst)
  (cond ((null? lst) '())
        (else (append (insert-everywhere item (car lst)) 
                    (insert-helper item (cdr lst))))))

but doing (permutations '(1 2 3)) just returns the empty list '().

© Stack Overflow or respective owner

Related posts about lisp

Related posts about Scheme