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 statement
1 Answer 1
I'd simplify as follows:
(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))
codePointAt
is a method of Java'sString
class.digit
is a static method of Java'sCharacter
class.
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 *))
;210
You 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)