我怎样才能获得与Common Lisp的一个列表中的所有可能的排列? [英] How can I get all possible permutations of a list with Common Lisp?

查看:245
本文介绍了我怎样才能获得与Common Lisp的一个列表中的所有可能的排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个Common Lisp的功能,这将使我一个列表的所有可能的排列,使用每个元素只有一次。例如,列表'(1 2 3)将得到的输出((1 2 3)(1 3 2)(2 1 3)(2 3 1)(3 1 2)(3 2 1))。

I'm trying to write a Common Lisp function that will give me all possible permutations of a list, using each element only once. For example, the list '(1 2 3) will give the output ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1)).

我已经写的东西,那种作品,但它的笨重,它并不总是工作,我甚至不真正了解它。我不要求为code,说不定关于如何去想一些指导。我不知道很多关于编写算法。

I already wrote something that kind of works, but it's clunky, it doesn't always work and I don't even really understand it. I'm not asking for code, just maybe for some guidance on how to think about it. I don't know much about writing algorithms.

谢谢, 杰森

推荐答案

作为一个基本方法,所有排列遵循这个递归模式:

As a basic approach, "all permutations" follow this recursive pattern:


  all permutations of a list L is:
    for each element E in L:
      that element prepended to all permutations of [ L with E removed ]

如果我们把所给,你必须在你的列表中没有重复的元素,下面应该做的:

If we take as given that you have no duplicate elements in your list, the following should do:


(defun all-permutations (list)
  (cond ((null list) nil)
        ((null (cdr list)) (list list))
        (t (loop for element in list
             append (mapcar (lambda (l) (cons element l))
                            (all-permutations (remove element list)))))))

这篇关于我怎样才能获得与Common Lisp的一个列表中的所有可能的排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆