Skip to content

Instantly share code, notes, and snippets.

@MrJaba
Last active August 29, 2015 14:28
Show Gist options
  • Save MrJaba/3ee82d75758be650965b to your computer and use it in GitHub Desktop.
Save MrJaba/3ee82d75758be650965b to your computer and use it in GitHub Desktop.
Various 4Clojure Problems
(ns tmp2)
(def data [1 1 2 3 2 1 1])
(def data2 [1 2 1 3 1 2 4])
( #(reduce (fn [acc el]
(if-not (some #{el} acc)
(conj acc el)
acc))
[] %) data2)
( #(apply merge-with + (for [i %] {i 1})) data )
(into {}(map (fn [xs] [(first xs) (count xs)] ) (partition-by identity (sort data))))
(fn [& fns]
(let [[f & r] (reverse fns)]
(fn [& data]
(reduce
(fn [args f]
(f args))
(apply f data)
r))))
(defn my-comp [& fs]
(let [[f & r] (reverse fs)]
(fn [& data] (reduce #(%2 %) (apply f data) r))))
((my-compose rest reverse) [1 2 3 4])
(defn my-juxt [& fns]
(fn [& data] (reduce (fn [acc f] (conj acc (apply f data))) [] fns)))
((my-juxt + max min) 2 3 5 1 6 4)
(rest (reverse [1 2 3 4]))
(defn sum-last-2
([] (sum-last-2 1 2))
([n m] (cons n (lazy-seq (sum-last-2 m (+ n m))))))
(take 6 (sum-last-2))
(defn my-reduce
([fxn coll]
(my-reduce fxn (first coll) (rest coll)))
([f val coll]
(if (seq coll)
(cons val (lazy-seq (my-reduce f (f val (first coll)) (rest coll))))
(cons val coll))))
(take 5 (my-reduce + (range)))
(my-reduce conj [1] [2 3 4])
(defn my-iterate [f x]
(cons x (lazy-seq (my-iterate f (f x)))))
(take 5 (my-iterate #(* 2 %) 1))
(defn my-group-by [f coll]
(reduce (fn [acc el]
(let [key (f el)]
(assoc acc key (conj (get acc key []) el))))
{} coll))
(my-group-by #(> % 5) [1 3 6 8])
(my-group-by #(apply / %) [[1 2] [2 4] [4 6] [3 6]])
(defn identify [coll]
(let [test-coll (conj coll [:xy :yz])
s (count test-coll)
f (first test-coll)
l (last test-coll)]
(if-not (associative? test-coll)
(cond
(= (count (conj test-coll f)) s ) :set
(not= (count (conj test-coll f)) s ) :list
)
(cond
(= (last (conj test-coll [:pq :pq] )) [:pq :pq] ) :vector
(not= (last (conj test-coll [:pq :pq] )) [:pq :pq]) :map)
)))
(identify {:a 1 :b 2})
(identify (range (rand-int 20)))
(identify [1 2 3 4 5 6])
(identify #{10 (rand-int 5)})
(map identify [{} #{} [] ()])
(defn gcd [x y]
(if (= 0 y)
x
(gcd y (rem x y))))
(defn sieve [n]
(let [candidates (range n)
primes (vec (concat [false false] (repeat (- n 1) true)))
max (+ 1(int (Math/sqrt n)))
sieved (reduce (fn [updated-primes i]
(if (nth primes i)
(reduce
(fn [i-updated-primes i-multiple]
(assoc i-updated-primes i-multiple false))
updated-primes
(range (* i i) n i))
updated-primes
))
primes
(range 2 max))]
(filter #(nth sieved %) candidates)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment