4
\$\begingroup\$

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
asked Dec 20, 2016 at 21:06
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

I'd simplify as follows:

(defn get-digit [x k] (Character/digit (.codePointAt x k) 10))
  • codePointAt is a method of Java's String class.
  • digit is a static method of Java's Character 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)
answered Dec 21, 2016 at 12:01
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.