返回n个布尔的所有组合的函数? [英] Function to return all combinations of n booleans?
问题描述
我试图实现一个函数,它接受一个数字n,并返回一个包含所有可能的n布尔组合的布尔列表的列表。例如, (make-bools 3)
应该像
I am trying to implement a function that takes a number n and returns a list of lists of booleans that contains all possible combinations of n booleans. The output of e.g. (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 ]]
数字从0到(2 ^ n)-1到二进制格式,并使用 bit-test
创建一个布尔列表,最后链接所有这些列表。但对我来说似乎很笨拙,我想必须有一个更优雅的解决方案。
I thought of converting the numbers from 0 to (2^n) - 1 to a binary format and use bit-test
to make a list of booleans, finally chaining all those lists. But that seems quite clumsy to me and I suppose there must be a more elegant solution.
推荐答案
我不知道是否被认为是欺骗使用现有库,而不是响应算法细节你的问题,但Clojure-contrib有一组常用的组合函数,用于计算排列:
I don't know if it's considered 'cheating' to use an existing library, rather than respond to the algorithmic details of your question, but Clojure-contrib has a set of common combinatorial functions that are 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
这篇关于返回n个布尔的所有组合的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!