patternMinor
Short Clojure digit extraction
Viewed 0 times
digitextractionclojureshort
Problem
I'm new to Clojure, and would appreciate feedback on this short program. The problem I set out to solve was selected at random from Project Euler, and is described in the comments. The part that I'm least happy about is the repeated series for the product, which I think could be replaced with a
reduce call somehow. ; An irrational decimal fraction is created by concatenating the positive integers:
; 0.123456789101112131415161718192021...
; ^
; It can be seen that the 12th digit of the fractional part is 1.
; If dn represents the nth digit of the fractional part,
; find the value of the following expression:
; d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
(def d (apply str (map str (range 1 1000001)))) ; generate Champernowne's contant
(defn get-digit [x k] (read-string (.substring x k (+ k 1)))) ; get digit at position
(* (get-digit d 0)
(get-digit d 9)
(get-digit d 99)
(get-digit d 999)
(get-digit d 9999)
(get-digit d 99999)
(get-digit d 999999)
) ; product from problem statementSolution
I'd simplify as follows:
Both of these are in
You can replace
The calculation may be easier to follow as a series of bindings in a
(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))codePointAtis a method of Java'sStringclass.
digitis a static method of Java'sCharacterclass.
Both of these are in
Java.lang, hence included by default. (->> 1
(iterate (partial * 10))
(map (comp (partial get-digit d) dec))
(take 7)
(apply *))
;210You can replace
apply with reduce, if you prefer. The calculation may be easier to follow as a series of bindings in a
let form:(let [powers-of-ten (iterate (partial * 10) 1)
digits (map (comp (partial get-digit d) dec) powers-of-ten)
seven-digits (take 7 digits)
answer (apply * seven-digits)]
answer)Code Snippets
(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))(->> 1
(iterate (partial * 10))
(map (comp (partial get-digit d) dec))
(take 7)
(apply *))
;210(let [powers-of-ten (iterate (partial * 10) 1)
digits (map (comp (partial get-digit d) dec) powers-of-ten)
seven-digits (take 7 digits)
answer (apply * seven-digits)]
answer)Context
StackExchange Code Review Q#150427, answer score: 4
Revisions (0)
No revisions yet.