Christopher’s posterous

Mostly programming things 
« Back to blog

Kaprekar's Number

I wrote some code in clojure to play around Kaprekar's Operation:
 

 
(defn fix 
 "Finds a fixed point of a function." 
 [f init-val] 
 (loop [last-val init-val 
  curr-val (f last-val)] 
  (if (= curr-val last-val) 
  curr-val 
  (recur curr-val (f curr-val))))) 
 
(defn sort-digits 
 "Sorts the digits in a number, default is ascending." 
 ([n] (sort-digits n true)) 
 ([n ascending?] 
  (let [cmp (if ascending? 
  #(.compareTo %1 %2) 
  #(.compareTo %2 %1))] 
  (Integer/parseInt (apply str (sort cmp (str n))))))) 
 
(defn kaprekar-operation 
 "Run one iteration of the kaprekar operation (e.g. 4321 - 1234)" 
 [n] 
 (- (sort-digits n false) (sort-digits n)))


(defn kaprekar-fix
 "Report on the fixed point of the Kaprekar operation starting
 from the INITIAL value (should be 6174 for 4-digit nums)" 
 [initial] 
 (fix kaprekar-operation initial)) 

 
If you call this like
(kaprekar-fix 2315)
you should get 6174.

Comments (0)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    Connect    twitter