Created
February 19, 2014 13:57
-
-
Save achin/9092570 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def add | |
{[\0 \0 \0] \0 | |
[\0 \0 \1] \1 | |
[\0 \1 \0] \1 | |
[\0 \1 \1] \0 | |
[\1 \0 \0] \1 | |
[\1 \0 \1] \0 | |
[\1 \1 \0] \0 | |
[\1 \1 \1] \1}) | |
(def carry | |
{[\0 \0 \0] \0 | |
[\0 \0 \1] \0 | |
[\0 \1 \0] \0 | |
[\0 \1 \1] \1 | |
[\1 \0 \0] \0 | |
[\1 \0 \1] \1 | |
[\1 \1 \0] \1 | |
[\1 \1 \1] \1}) | |
(defn fill [s n] | |
(take n (concat s (repeat \0)))) | |
(defn add-bits [{:keys [sum c]} [a b]] | |
{:sum (cons (add [a b c]) sum) | |
:c (carry [a b c])}) | |
(defn sum->str [{:keys [sum c]}] | |
(apply str c sum)) | |
(defn add-binary-strings [x y] | |
(let [n (max (count x) (count y)) | |
xs (fill (reverse x) n) | |
ys (fill (reverse y) n)] | |
(->> (map vector xs ys) | |
(reduce add-bits {:sum nil, :c \0}) | |
sum->str))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment