2010-06-03 4 views
6

Ma réponse à ce problem ressemble trop à ces solutions in C.Projet Euler # 9 (triplets de Pythagore) dans Clojure

Quelqu'un a-t-il des conseils pour rendre cela plus lispy?

(use 'clojure.test) 
(:import 'java.lang.Math) 

(with-test 
    (defn find-triplet-product 
    ([target] (find-triplet-product 1 1 target)) 
    ([a b target] 
     (let [c (Math/sqrt (+ (* a a) (* b b)))] 
     (let [sum (+ a b c)] 
      (cond 
      (> a target) "ERROR" 
      (= sum target) (reduce * (list a b (int c))) 
      (> sum target) (recur (inc a) 1 target) 
      (< sum target) (recur a (inc b) target)))))) 

    (is (= (find-triplet-product 1000) 31875000))) 

Répondre

4

j'ai personnellement utilisé cet algorithme (que j'ai trouvé décrit here):

(defn generate-triple [n] 
    (loop [m (inc n)] 
    (let [a (- (* m m) (* n n)) 
      b (* 2 (* m n)) c (+ (* m m) (* n n)) sum (+ a b c)] 
     (if (>= sum 1000) 
     [a b c sum] 
     (recur (inc m)))))) 

Il me semble beaucoup moins compliqué :-)

Questions connexes