Skip to content

Instantly share code, notes, and snippets.

@achin
Created February 19, 2014 13:57
Show Gist options
  • Save achin/9092570 to your computer and use it in GitHub Desktop.
Save achin/9092570 to your computer and use it in GitHub Desktop.
(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