Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating binary numbers of n digits in clojure

Tags:

clojure

I'd like to generate binary numbers of n digits from 0 to 2^n-1. For example of 3 digits, "000", "001", "010", ..., "111" (0 to 7 in decimal). The way I used is to use java.lang.Integer.toBinaryString() method and add zeros if necessary like the following:

(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)))))

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

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

But this codes look a little verbose. Aren't there any ways better or more clojure way to do this?

like image 413
ntalbs Avatar asked Aug 22 '12 03:08

ntalbs


1 Answers

You can simplify the formatting using 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) is equivalent to (bit-shift-left 1 n).

Another way to express this would be in term of selections from clojure.math.combinatorics:

(defn binary-permutation [n]
  (map (partial apply str) (selections [0 1] n)))
like image 118
Alex Jasmin Avatar answered Sep 30 '22 18:09

Alex Jasmin