diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2021-04-03 23:33:35 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-04-03 23:33:35 +0100 |
| commit | ecf33634ff2d9c1772ffb8a50d9be8ae22f9e0cd (patch) | |
| tree | 7ad856779ef0dead3dbb0b4bf4290a256080993e /challenge-106/tyler-wardhaugh/clojure/src/tw/weekly/c106/t2.clj | |
| parent | 083a2924aaf385cb100eb6e73c813339f062b590 (diff) | |
| parent | c8cf311317835bd08e0fdaf476519cf3de7ddf2c (diff) | |
| download | perlweeklychallenge-club-ecf33634ff2d9c1772ffb8a50d9be8ae22f9e0cd.tar.gz perlweeklychallenge-club-ecf33634ff2d9c1772ffb8a50d9be8ae22f9e0cd.tar.bz2 perlweeklychallenge-club-ecf33634ff2d9c1772ffb8a50d9be8ae22f9e0cd.zip | |
Merge pull request #3818 from tylerw/tw/challenge-106
Ch106 (Clojure): Tasks 1 & 2
Diffstat (limited to 'challenge-106/tyler-wardhaugh/clojure/src/tw/weekly/c106/t2.clj')
| -rw-r--r-- | challenge-106/tyler-wardhaugh/clojure/src/tw/weekly/c106/t2.clj | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/challenge-106/tyler-wardhaugh/clojure/src/tw/weekly/c106/t2.clj b/challenge-106/tyler-wardhaugh/clojure/src/tw/weekly/c106/t2.clj new file mode 100644 index 0000000000..d48c6e3b0e --- /dev/null +++ b/challenge-106/tyler-wardhaugh/clojure/src/tw/weekly/c106/t2.clj @@ -0,0 +1,43 @@ +(ns tw.weekly.c106.t2 + (:require [clojure.edn :as edn] + [clojure.math.numeric-tower :refer [abs]])) + +;;; +; Task description for TASK #2 › Decimal String +;;; +(def DEFAULT-INPUT [1 3]) + +(defn- decimal-string-recurring + "Covert the given n[umerator] and d[enominator] (which must be known to + have a recurring fractional result) into a decimal string where the recurring + fractional is put in parenthesis." + [n d] + (loop [remainder (abs (rem n d)) + cache {} + result []] + (if (not (or (zero? remainder) (cache remainder))) + (recur (rem (* 10 remainder) d) + (assoc cache remainder (count (apply str result))) + (conj result (quot (* 10 remainder) d))) + (let [[lead recurrence] (->> result (split-at (get cache remainder 0))) + whole (quot n d) + pieces (concat [whole \.] lead [\(] recurrence [\)])] + (apply str pieces))))) + +(defn decimal-string + "Covert the given n[umerator] and d[enominator] into a decimal string where any + recurring fractional is put in parenthesis." + [n d] + (try (str (/ (bigdec n) d)) + (catch ArithmeticException _ + ; BigDecimal throws this exception when the result cannot be + ; represented with the 'UNLIMITED' precision (the default), i.e., + ; there is a recurring fractional result + (decimal-string-recurring n d)))) + +(defn -main + "Run Task 2 with a given N and D, defaulting to the example given in the task + description." + [& args] + (let [[N D] (or (some->> args (take 2) (map edn/read-string)) DEFAULT-INPUT)] + (println (decimal-string N D)))) |
