Skip to content

Instantly share code, notes, and snippets.

@noahlz
Created December 25, 2011 00:50
Show Gist options
  • Save noahlz/1518577 to your computer and use it in GitHub Desktop.
Save noahlz/1518577 to your computer and use it in GitHub Desktop.
LabREPL Project Euler exercises
;; "Find the sum of all the multiples of 3 or 5 below 1000."
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Filtering
;; "Create a divides? predicate that takes a dividend and a divisor, and returns true if divisor evenly
;; divides the dividend"
;; My solution to the filtering "divides?" problem:
(defn divides? [num div] (= 0 (mod num div)))
;; The solution
(defn divides?
"Does divisor divide dividend evenly?"
[dividend divisor]
(zero? (rem dividend divisor)))
;; "create a divides-any function that takes a variable list of numbers, and returns a predicate
;; that tests whether its arg can be evenly divided by any of the numbers.
;; (Hint: work inside-out, using divides?, some, and boolean)."
;; The solution:
(defn divides-any
[& nums]
(fn [arg]
(boolean (some #(divides? arg %) nums))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A Solution by Reduction
;; "create a sequence of all the values that should contribute to the sum, and then simply add them."
;; My partial solution to "Solution by Reduction" problem (I didn't define the function):
(for [x (range 20) :let [y x divides-3-or-5 (divides-any 3 5)]
:when (divides-3-or-5 y)] y)
;; (0 3 5 6 9 10 12 15 18)
(reduce + (for [x (range 20) :let [y x divides-3-or-5 (divides-any 3 5)]
:when (divides-3-or-5 y)] y))
;; 78
;; The official solution:
(defn problem-1
([] (problem-1 1000))
([upper]
(apply + (filter (divides-any 3 5) (range upper)))))
(problem-1 20)
;; 78
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A Left-To-Right Solution
;; My Solution
(defn problem-2
([] problem-2 1000)
([upper]
(->> (range upper) (filter (divides-any 3 5)) (apply +))))
(problem-2 20)
;; 78
;; The official solution
(defn problem-1-left-to-right
"Sum the numbers divisible by 3 or 5, from 0 to upper."
([] (problem-1-left-to-right 1000))
([upper]
(->> (range upper)
(filter (divides-any 3 5))
(apply +))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Working with filter some more:
(filter #(zero? (rem % 2)) (range 30))
;; (0 2 4 6 8 10 12 14 16 18 20 22 24 26 28)
(defn palindrome? [s]
(= s (->> (reverse s) (apply str))))
;; NOTE: not the best implementation...
(palindrome? "blah")
;; false
(palindrome? "bab")
;; true
(palindrome? "blahhalb")
;; true
(filter palindrome? ["blah" "bab" "blahhalb"])
;; ("bab" "blahhalb")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment