Skip to content

Instantly share code, notes, and snippets.

@robjens
Last active January 18, 2017 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robjens/585e1919db2439418f4ede00cca8c53e to your computer and use it in GitHub Desktop.
Save robjens/585e1919db2439418f4ede00cca8c53e to your computer and use it in GitHub Desktop.
Scratch of Clojure print-matrix functions string->square
(require '[clojure.string :as string])
(defn square-len?
[s] (= (mod (Math/sqrt (count s))
1)
0.0))
(defn dimensions
"Takes a string s and returns the square root of its length as an integer.
e.g. 2.123 => 2, 2.0 => 2"
[s] (some-> s count Math/sqrt int))
(defn partial=
"Partial function application, takes a value x and returns a function taking
value y comparing x to y and returning true when equal."
[x] (fn [y] (= x y)))
(def nul? (partial= \0))
(def one? (partial= \1))
(def binary? (partial every? (some-fn nul? one?)))
;(binary? "010102") ;=> false
;(binary? "010101") ;=> true
(defn ->matrix [s]
(when ((every-pred binary? square-len?) s)
(some-> s dimensions (partition s)
(some->> (mapv vec)))))
;;; print matrices
(defn underline [labels]
(str "|" (string/join (interpose "+"
(repeat (inc (count labels))
"---"))) "|"))
(defn headline [labels]
(str "| # | " (string/join " | " labels) " |"))
(defn rowlines [rows]
(map (partial string/join "")
(map-indexed #(conj (vec (cons (str "| " (inc %1) " ¦ ")
(interpose " | " %2)))
" |")
rows)))
(defn bidirectional? [x y bs]
(let [mx (->matrix bs)
x->y (= \1 (nth (nth mx (dec x)) (dec y)))
y->x (= \1 (nth (nth mx (dec y)) (dec x)))]
(and x->y y->x)))
;; (bidirectional? 2 3 "1010100111010110101100101") ;=> true
(defn print-matrix [s]
(when-let [xs (->matrix s)]
(let [nlabels (some->> xs first count inc (range 1))
str-seq (some->> (rowlines xs)
(vector (headline nlabels)
(underline nlabels))
flatten)]
(doseq [x str-seq]
(println x)))))
(print-matrix "101010011101011010110010") ;=> nil
(print-matrix "101010011101011010110010I") ;=> nil
(print-matrix "1010100111010110101100101") ;=>
;; | # | 1 | 2 | 3 | 4 | 5 |
;; |---+---+---+---+---+---|
;; | 1 ¦ 1 | 0 | 1 | 0 | 1 |
;; | 2 ¦ 0 | 0 | 1 | 1 | 1 |
;; | 3 ¦ 0 | 1 | 0 | 1 | 1 |
;; | 4 ¦ 0 | 1 | 0 | 1 | 1 |
;; | 5 ¦ 0 | 0 | 1 | 0 | 1 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment