recursion - Clojure: Write a Clojure function that returns a list of all 2^n bits strings of length n -
i want write clojure function called (nbits n) returns list of 2^n bits strings of length n.
my expected output is:
user=> (nbits -2) () user=> (nbits 0) () user=> (nbits 1) ((0) (1)) user=> (nbits 2) ((0 0) (0 1) (1 0) (1 1)) user=> (nbits 3) ((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1))
here try:
(defn add0 [seq] (cond (empty? seq) 'nil (and (seq? seq) (> (count seq) 0)) (cons (cons '0 (first seq)) (add0 (rest seq))))) (defn add1 [seq] (cond (empty? seq) 'nil (and (seq? seq) (> (count seq) 0)) (cons (cons '1 (first seq)) (add1 (rest seq))))) (defn nbits [n] (cond (number? n) (cond (< n 1) '() (= n 1) '((0) (1)) (> n 1) (list (add0 (nbits (- n 1))) (add1 (nbits (- n 1))))) :else 'nil))
but output not right. did go wrong? don't know how fix it.
you (lazily , iteratively) math.combinatorics library:
user=> (defn nbits [n] (if (pos? n) (clojure.math.combinatorics/selections [0 1] n) '())) #'user/nbits user=> (nbits 0) () user=> (nbits 1) ((0) (1)) user=> (nbits 2) ((0 0) (0 1) (1 0) (1 1)) user=> (nbits 3) ((0 0 0) (0 0 1) (0 1 0) (0 1 1) (1 0 0) (1 0 1) (1 1 0) (1 1 1))
this version has advantage of leveraging iteration avoid blowing stack (which got @ n=14 original version on machine).
Comments
Post a Comment