Skip to content

Instantly share code, notes, and snippets.

@sashton
Created February 5, 2016 04:04
Show Gist options
  • Save sashton/b5da3bf6038d7aa759f4 to your computer and use it in GitHub Desktop.
Save sashton/b5da3bf6038d7aa759f4 to your computer and use it in GitHub Desktop.
(ns programming-problems.template
(:import (java.io BufferedReader ByteArrayInputStream InputStreamReader)))
; STDIN generator ------------------------------
(defn str->reader [str]
(BufferedReader. (InputStreamReader. (ByteArrayInputStream. (.getBytes str)))))
(defn dev-stdin []
(str->reader ""))
; Input ------------------------------
(defn wrap-stdin* [f]
(binding [*in* (if-let [stdin-gen (resolve 'dev-stdin)]
(stdin-gen)
*in*)]
(f)))
(defmacro wrap-stdin [& body]
`(wrap-stdin* #(do ~@body)))
(defn str->int [s] (Integer/parseInt s))
(defn parse-num-line [line]
(->> (clojure.string/split line #" ")
(map str->int)))
(defn get-n-lines [n]
(for [_ (range n)]
(read-line)))
(defn read-int []
(str->int (read-line)))
(defn read-vector []
(parse-num-line (read-line)))
; Maths -------------------------------
(defn gcd [a b]
(if (pos? b)
(recur b (mod a b))
a))
(defn lcm [a b]
(* b (/ a (gcd a b))))
(defn str->digits [s]
(map #(- (int %) 48) s))
(defn divisible-by [n]
(fn [x] (zero? (mod x n))))
(defn factor-of [n]
(fn [x]
(and (not (zero? x))
(zero? (mod n x)))))
; Test Harness -------------------------------------
(defn run-n-tests [n test-fn]
(doseq [_ (range n)]
(println (test-fn (read-line)))))
(defn run-with-test-count [test-fn]
(let [len (str->int (read-line))]
(run-n-tests len test-fn)))
; Test ---------------------------------------------
; Start ----------------------------------------------
(wrap-stdin (println "done"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment