public
Created

Solutions to problems from the clojure-workshop @ Melbourne (March 2013)

  • Download Gist
solutions.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
(defn multiples [n]
(let [all (range n)
pred #(or (= 0 (mod % 3)) (= 0 (mod % 5)))]
(reduce + (filter pred all))))
 
;(println (multiples 10)) ; => 23
;(println (multiples 1000)) ; => 233168
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
;lazy fibonacci from slides...
(defn fib [a b] (cons a (lazy-seq (fib b (+ b a)))))
 
(defn sum-even-fib [max_n]
(let [pred #(< % max_n)]
(apply + (filter even? (take-while pred (fib 1 2))))))
 
;(println (sum-even-fib 90)) ; => 44
;(println (sum-even-fib 4000000)) ; => 4613732
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
(defn is-palindrome? [n]
(let [str-n (str n)
reversed (apply str (reverse str-n))]
(= str-n reversed)))
 
;(println "101 is palindrome?" (is-palindrome? 101)) ; => true
 
(defn list-palindromes [digits]
(let [maxn (apply * (repeat digits 10))]
(filter is-palindrome? (for [x (range maxn)
y (range maxn)]
(* x y)))))
 
;(println (apply max (list-palindromes 2))) ; => 9009
;(println (apply max (list-palindromes 3))) ; => 906609
 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
(defn apply-divisor [divisor initial-seq]
(filter #(= 0 (mod % divisor)) initial-seq))
 
(defn apply-divisors [divisors initial-seq]
(let [[divisor & more] divisors]
(cond
(empty? more) (apply-divisor divisor initial-seq)
:else (recur more (apply-divisor divisor initial-seq)))))
 
(defn smallest-multiple [max-divisor]
(first (drop 1 (apply-divisors (range 2 (inc max-divisor)) (range)))))
 
;(println (smallest-multiple 10)) ; => 2520
;(println (smallest-multiple 20)) ; => 232792560

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.