返回n个布尔的所有组合的函数?

编程入门 行业动态 更新时间:2024-10-25 09:35:13
本文介绍了返回n个布尔的所有组合的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图实现一个函数,它接受一个数字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.contribbinatorics :as comb]) (defn make-bools [n] (apply comb/cartesian-product (repeat n [true false])))

richhickey.github/clojure-contrib/combinatorics-api.html

更多推荐

返回n个布尔的所有组合的函数?

本文发布于:2023-11-29 18:29:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647239.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   布尔   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!