clojure - get combinations of vector elements -


i wander if there reducer in clojure can give same result below function without using recursion

the function should take vector , returns combinations of items (e.g. giving [1 2 3] , returns ((1 2 3) (1 2) (1 3) (1) (2 3) (2) (3) []))

(def combinations "creates combinations of items example [1 2 3] 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)))))) 

an alternative approach use clojure math lib.

for leiningen project.clj add this- [org.clojure/math.combinatorics "0.1.3"]

to use-

(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)) 

you can see source code here recursion-less solution if don't want lib.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -