Generating binary numbers from n digits in clojure

I would like to generate binary numbers n digits from 0 to 2 ^ n-1. For example, 3 digits: "000", "001", "010", ..., "111" (from 0 to 7 in the decimal system). I used the java.lang.Integer.toBinaryString() method and added zeros if necessary, as shown below:

 (defn pad-zero [sn] (str (reduce str (repeat (- n (count s)) "0")) s)) (defn binary-permutation [n] (map (fn [s] (pad-zero sn)) (map #(Integer/toBinaryString %) (range 0 (Math/pow 2 n))))) 

With this code, I can create what I want, like this. For 3 digits:

 (binary-permutation 3) => ("000" "001" "010" "011" "100" "101" "110" "111") 

But these codes look a bit detailed. Are there no ways to improve or a more clojure way to do this?

+6
source share
2 answers

You can simplify formatting with cl-format from clojure.pprint :

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

You may also be interested to know that (Math/pow 2 n) equivalent to (bit-shift-left 1 n) .

Another way to express this would be as options from clojure.math.combinatorics :

 (defn binary-permutation [n] (map (partial apply str) (selections [0 1] n))) 
+7
source
 (defn binary-permutation [n] (for [x (range (Math/pow 2 n))] (apply str (reverse (take n (map #(bit-and 1 %) (iterate #(bit-shift-right % 1) x))))))) (defn pad-zero [sn] (apply str (take-last n (concat (repeat n \0) s)))) 
+2
source

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


All Articles