Skip to content

Instantly share code, notes, and snippets.

@ppsdatta
Last active October 4, 2021 13:39
Show Gist options
  • Save ppsdatta/75b316b72b0a17bdba340c41ead9dc24 to your computer and use it in GitHub Desktop.
Save ppsdatta/75b316b72b0a17bdba340c41ead9dc24 to your computer and use it in GitHub Desktop.
A collection of useful Clojure functions

Read next value from stdin

(defn next-seq
  [& {:keys [sep type] :or {sep " " type nil}}]
  (let [line (read-line)
        parts (clojure.string/split line (re-pattern sep))]
    (case type
      :int (map #(Integer/parseInt %) parts)
      :double (map #(Double/parseDouble %) parts)
      :line (clojure.string/join " " parts)
      parts)))

(defn next-int
  []
  (first (next-seq :type :int)))

(defn next-double
  []
  (first (next-seq :type :double)))

(defn next-value
  []
  (first (next-seq)))
  
(defn next-line
  []
  (next-seq :type :line))

Check if n is prime

(defn prime?
 [n]
 (cond
   (< n 2) false
   (= n 2) true
   (= (rem n 2) 0) false
   (some (fn [x] (= (rem n x) 0)) (range 2 (inc (Math/sqrt n)))) false
   :else true))

find-first and find-last lazily in a sequence

(defn find-first
  [seq pred]
  (first (filter pred seq)))

(defn find-last
  [seq pred]
  (first (filter pred (reverse seq))))

Permutations of a sequence

(defn perms
   [s]
   (cond
     (empty? s) [[]]
     true (mapcat 
           (fn [i]
             (map (fn [p] (conj p i))
                  (perms (filter #(not (= % i)) s))))
           s)))

Find all numbers within a range all numbers which are divisible by every number between 1 to 10

(defn find-nums [frm to]
  "Find all numbers in the inclusive range (frm, to)
   which can be divided by all number between (1, 10)"
  (->> (range frm (+ to 1))
       (map (fn [num]
              [num
               (->> (range 1 11)
                    (map #(= (rem num %) 0))
                    (map #(if (not %) 0 1))
                    (reduce +))]))
       (filter #(= (second %) 10))
       (map first)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment