Does the function return all combinations of n boolean elements?

I am trying to implement a function that takes a number n and returns a list of logical element lists containing all possible combinations of n Booleans. The output, for example (make-bools 3) should look like

 [[false false false] [false false true ] [false true false] [false true true ] [true false false] [true false true ] [true true false] [true true true ]] 

I was thinking about converting numbers from 0 to (2 ^ n) - 1 in binary format and use bit-test to make a list of logical elements, finally linking all these lists. But that seems rather awkward to me, and I believe there should be a more elegant solution.

+4
source share
3 answers

I donโ€™t know if he considered it a โ€œtrickโ€ to use the existing library and not answer the algorithmic details of your question, but Clojure -contrib has a set of common combinatorial functions useful for calculating permutations

 (require '[clojure.contrib.combinatorics :as comb]) (defn make-bools [n] (apply comb/cartesian-product (repeat n [true false]))) 

http://richhickey.github.com/clojure-contrib/combinatorics-api.html

+3
source

also works great

 (let [bools [false true]] (for [x bools y bools z bools] [xyz])) 
+2
source

If you are still looking for a recursive solution from scratch (if only for learning), here, where a template is implemented that is often useful for recursively building โ€œpathsโ€ through tree structures:

 (let [bools [true false]] (fn combs [n] (if (zero? n) [[]] (for [smaller (combs (dec n)) b bools] (cons b smaller))))) 

In this case, the โ€œtreeโ€ is imaginary (a series of true / false choices), but the same methods apply.

+2
source

Source: https://habr.com/ru/post/1389893/


All Articles