簡體   English   中英

Lisp:如何從列表中包含的列表中獲取所有可能的元素組合?

[英]Lisp: How to get all possible combinations of the elements from lists contained on a list?

我需要在Common-Lisp中編寫一個函數,該函數獲取列表列表並返回一個列表,其中包含子列表中元素的所有可能組合。

因此,例如,在諸如((1 2)(1 2))之類的列表上調用該函數應該返回類似((1 1)(1 2)(2 1)(2 2))的列表。 輸入列表可以是任意長度,並且子列表不保證具有相同的長度。

我知道如何使用子列表中的成對元素(inputtting((1 2)(1 2))返回((1 1)(2 2)),但這對於弧一致性算法來說還不夠好我是試着寫,我被卡住了。

謝謝。

wvxvw刪除了他們的答案,指向亞歷山大的一個函數,但它確實提供了一個非常相似的命名函數,實際上做你想要的。 而不是alexandria:map-combinations ,你需要alexandria:map-product ,例如

(apply #'alexandria:map-product #'list '((1 2) (1 2)))

評估為

((1 1) (1 2) (2 1) (2 2))

如果您不想使用庫,這里的代碼可以執行相同的操作,並且可以使用任意數量的列表:

(defun combinations (&rest lists)
  (if (endp lists)
      (list nil)
      (mapcan (lambda (inner-val)
                (mapcar (lambda (outer-val)
                          (cons outer-val
                                inner-val))
                        (car lists)))
              (apply #'combinations (cdr lists)))))

[2]> (combinations '(1 2))
((1) (2))
[3]> (combinations '(1 2) '(3 4))
((1 3) (2 3) (1 4) (2 4))
[4]> (combinations '(1 2) '(3 4) '(5 6))
((1 3 5) (2 3 5) (1 4 5) (2 4 5) (1 3 6) (2 3 6) (1 4 6) (2 4 6))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM