生成列表的排列
我正在编写一个函数,它接受一个列表并返回参数的排列列表。
我知道如何通过使用删除元素的函数,然后递归地使用该函数来生成所有排列来做到这一点。我现在遇到一个问题,我想使用以下函数:
(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))
该函数会将项目插入到列表的每个可能的位置,如下所示:
(insert-everywhere 1 '(a b))
will get:
'((1 a b) (a 1 b) (a b 1))
我将如何使用此函数来获取列表的所有排列?
我现在有:
(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))))))
但是执行 (permutations '(1 2 3))
只是返回空列表 '()
。
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 '()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,构建一系列相关示例:
弄清楚每个答案与其前面的答案之间的关系。也就是说,给定前一个答案(列表尾部)和列表头部的新元素,如何计算每个答案?
First, construct a family of related examples:
Figure out how each answer is related to the one before it. That is, how can you calculate each answer given the previous answer (for the tail of the list) and the new element at the head of the list?
这是一个函数,它生成大小为 'size' 的数字的所有排列,它由列表 'items' 中的元素组成
Here is a function, that generates all permutations of numbers with size 'size' , that it consisted of the elements in the list 'items'