得到

2016-09-22 39 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的递归少解决方案,如果不想库。