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?
source share