在clojure中生成n位数的二进制数

nta*_*lbs 6 clojure

我想生成n从0到2 ^ n-1的二进制数字.例如3位数,"000","001","010",......,"111"(十进制0到7).我使用的java.lang.Integer.toBinaryString()方法是使用方法并在必要时添加零,如下所示:

(defn pad-zero [s n]
  (str (reduce str (repeat (- n (count s)) "0")) s))

(defn binary-permutation [n]
  (map (fn [s] (pad-zero s n))
       (map #(Integer/toBinaryString %) (range 0 (Math/pow 2 n)))))
Run Code Online (Sandbox Code Playgroud)

使用此代码,我可以生成我想要的内容.3位数:

(binary-permutation 3)
=> ("000" "001" "010" "011" "100" "101" "110" "111")
Run Code Online (Sandbox Code Playgroud)

但这些代码看起来有点冗长.有没有更好的方法或更多的方法来做到这一点?

Ale*_*min 7

您可以使用简化格式CL-格式clojure.pprint:

(defn binary-permutation [n]
  (map (partial cl-format nil "~v,'0B" n) (range 0 (Math/pow 2 n))))
Run Code Online (Sandbox Code Playgroud)

您可能也有兴趣知道这(Math/pow 2 n)相当于(bit-shift-left 1 n).

表达这一点的另一种方式是从clojure.math.combinatorics选择:

(defn binary-permutation [n]
  (map (partial apply str) (selections [0 1] n)))
Run Code Online (Sandbox Code Playgroud)