得到

2016-09-22 17 views
0

我只是遊蕩,如果有Clojure中的任何減速,可以給相同的結果,下面的功能,而無需使用遞歸得到

功能應採取一個向量,並返回其項目的組合矢量元素的組合(例如給予[ 1 2 3]和返回((1 2 3)(1 2)(1 3)(1)(2 3)(2)(3)[]))

(def combinations 
"creates combinations of items for example [1 2 3] 
will generate ((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) [])" 
(memoize (fn[items] 
(if (empty? items) [[]] 
(let [els (combinations (rest items))] 
    (concat (map #(cons (first items) %)els) els)))))) 

回答

3

一種替代方法將是使用Clojure數學庫。

對於leiningen project.clj添加這個 - [org.clojure/math.combinatorics "0.1.3"]

要使用 -

(ns example.core 
    (:require [clojure.math.combinatorics :as c])) 

(c/subsets [1 2 3]) 
;;=> (() (1) (2) (3) (1 2) (1 3) (2 3) (1 2 3)) 

你可以看到源代碼here的遞歸少解決方案,如果不想庫。