Thursday, August 18, 2011

Shortness

When I first watched intro videos for learning clojure, the thing that I was most sceptical about is shortness of a code. Little did I know! I`ve put up a couple of examples to prove it to those that still think the way I did.

Euler Problem 052

(defn digits [big-n]
  (map read-string (re-seq #"\d+" (apply str (interleave (repeat ",") (seq (str big-n)))))))   

I`m certain there is a straightforward way to get digits from a number in clojure, but I haven`t found it. And not for the lack of trying! But this is the best I could come up with.

(defn eligible? [n l]
  (loop [i n c 1]
    (if (= c l) true (if (= (sort (digits n)) (sort (digits (+ n i)))) (recur (+ n i) (inc c)) false))))

The second function checks if the number in question does have the same digits when multiplied l times. L stands for limit, meaning how many times should the number be multiplied. Number digits is sorted, and then compared to the double of its values digits. If they are the same, then double and triple values are compared and so on.

(time (println (#(if (eligible? % %2) % (recur (inc %) %2)) 1 6)))

Finally, I use brute force in the anonymous function to check each number if it fulfills the terms of the assignment. It just increments numbers one by one, nothing fancy.


4Clojure Number maze

(fn [s e]
  (loop [n 1 coll #{s}]s
    (if (contains? coll e) n
      (recur (inc n) (set (flatten (for [p (vec coll)] (map #(% p 2) [+ / *]))))))))
 Function takes the starting number and checks if it matches the end. If it doesn`t, the next iteration takes 3 new values as an arg, one for each operation. So each next iteration has 3 args in a coll for each of the previous args. Perfect example of using higher order function in clojure, imo.

So yes, clojure code is short. And if you`re not convinced, check this. Make sure to read through the comments as well!

There is a naughty saying among Serbian developers saying that..., well, I`m not gonna say that in public, but it means that you have more time on your hands when you type less.

update, 16.09.2011:


Finally, I took some time to find better digits function. Here it is:

(defn digits [big-n]
 (map (Character/getNumericValue %) (str n)))

No comments:

Post a Comment