Skip to content

Instantly share code, notes, and snippets.

@jreighley
Created January 20, 2020 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jreighley/4c2245ecf708421151ec1031913437f5 to your computer and use it in GitHub Desktop.
Save jreighley/4c2245ecf708421151ec1031913437f5 to your computer and use it in GitHub Desktop.
(ns scratches.gapful)
(comment
Challenge from https://purelyfunctional.tv/issues/purelyfunctional-tv-newsletter-361-tip-trampoline-your-tail-recursion/
Some numbers are gapful, some aren't. 100 is gapful because it has at least three digits and 100 is divisible by 10 ((str 1 0), the concatenation of the first and last digit). That's the definition of gapful: it has at least three digits and is divisible by the number formed by concatenating the first and last digits.
Create a function that takes a number and finds the closest gapful number. The function should return its argument if the argument itself is gapful. And if there are two gapful numbers equidistant to the argument, return the lower {one.})
(defn concat-fl
"concatates first and last digits of a number"
[n]
(let [nstr (seq (.toString n))]
(Integer/parseInt (str (first nstr) (last nstr)))))
(defn gapful?
"predicate to indicate if a number is 100 or more and divisible by it's first and last digits"
[n]
(let [fl-concat (concat-fl n)]
(if (and (>= n 100)
(= 0 (mod n fl-concat)))
true
false)))
;lazy sequence of gapful numbers
(def gapful-seq
(filter #(gapful? %) (range)))
(defn find-nearest-gapful
"Finds nearest gapful number. if equal distant, returns lowest number"[n]
(let [sm-gapful (last (take-while #(>= n %) gapful-seq))
lg-gapful (first (filter #(<= n % ) gapful-seq))]
(if sm-gapful (if (< (- lg-gapful n) (- n sm-gapful )) lg-gapful sm-gapful)
lg-gapful)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment