Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Last active April 13, 2019 14:04
Show Gist options
  • Save ericnormand/724470d1d218de3a3fc045388bceaedf to your computer and use it in GitHub Desktop.
Save ericnormand/724470d1d218de3a3fc045388bceaedf to your computer and use it in GitHub Desktop.
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:require [schema.core :as s]
[clojure.string :as str]))
(s/defn divisible-by-3 :- s/Str
[binary-str-all]
(let [binstr-div-by-3? (s/fn [binstr :- s/Str]
(it-> binstr
(Integer/parseInt it 2)
(mod it 3)
(zero? it)))]
(it-> binary-str-all
(str/split it #",")
(keep-if binstr-div-by-3? it)
(str/join "," it))))
(dotest
(is= (divisible-by-3 "1100,101,111,1111")
"1100,1111"))
(defn filter-bin-str-divisible-n
"filter comma separated str represented binary numbers when divisible by n (default 3)"
([input] (filter-bin-str-divisible-n input 3))
([input divisor]
(as-> input $
(clojure.string/split $ #",")
(filter #(= 0 (mod (Integer/parseInt % 2) divisor)) $)
(clojure.string/join "," $))))
(filter-bin-str-divisible-n "1100,101,111,1111")
;; => "1100,1111"
(filter-bin-str-divisible-n "1100,101,111,1111" 5)
;; => "101,1111"
(ns pf-1.core
(:gen-class))
(def input-string "1100, 101, 111, 1111, 011, 100001, 111110")
(defn input-string-to-tokens
"Convert input like \"1101, 101\" to trimmed tokens of the form '1101'"
[input-string]
(map clojure.string/trim (clojure.string/split input-string #",")))
(defn convert-token-to-binseq
"Convert a token of the form '1101' to a sequence (1 1 0 1)"
[token]
(map
#(- (int %) 48) ;char '1' is 49 when forced to int
(char-array token)))
(defn binseq-to-number
"Convert a sequence like (1 0 0 1) to an integer, it does this by zipping the sequence with the corresponding binary factors and accumulating these factors"
[s]
(reduce
(fn
[acc val]
(if (= 1 (second val))
(+ acc (first val))
acc)
)
0
(zipmap
(map #(int (Math/pow 2 %)) (range (count s)))
s)))
(defn do-our-thing
[input-string]
(->> input-string ;"111, 1100, 11"
input-string-to-tokens ;("111" "1100" "11")
(map convert-token-to-binseq) ;((1 1 1) (1 1 0 0) (1 1))
(filter
#(= 0 (mod (binseq-to-number %) 3))) ;((1 1 0 0) (1 1))
(map clojure.string/join) ;("1100" "11")
(clojure.string/join ",") ;"1100, 11"
))
(defn -main
[& args]
(println input-string)
(println (do-our-thing input-string)))
(require '[clojure.string :as str])
(defn bdiv5 [bstr]
(->> (when-not (str/blank? bstr) (str/split bstr #","))
(map #(Long/parseLong % 2))
(filter #(zero? (rem % 5)))
(map #(Long/toBinaryString %))
(str/join ",")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment