Skip to content

Instantly share code, notes, and snippets.

@devstopfix
Created December 15, 2016 20:36
Show Gist options
  • Save devstopfix/357c4ebeb3c27d2001cd1030980e1ad3 to your computer and use it in GitHub Desktop.
Save devstopfix/357c4ebeb3c27d2001cd1030980e1ad3 to your computer and use it in GitHub Desktop.
Zuhlke UK coding night - parse binary string
(ns zuhlke.codingnight.binary)
;
; Coding night challenge - Binary
; Convert string of binary digits to int
;
(defn binary-str-to-int [s]
(loop [s (reverse s)
acc 0
pwr 1]
(if-let [x (first s)]
(recur (rest s)
(+ acc (* pwr (Integer. (str x))))
(* 2 pwr))
acc)))
; Tests
(require '[clojure.test.check :as tc])
(require '[clojure.test.check.generators :as gen])
(require '[clojure.test.check.properties :as prop])
(def binary-digit (gen/elements [\0 \1]))
(def binary-string
(->>
(gen/vector binary-digit 1 62)
(gen/fmap clojure.string/join)))
(tc/quick-check 1000
(prop/for-all [s binary-string]
(= (BigInteger. s 2) (binary-str-to-int s))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment