Hi,

On Fri, Oct 9, 2009 at 7:22 PM, vishy <vishalsod...@gmail.com> wrote:

>
> I was attempting problem no 4 at projecteuler.net. The solution I came
> up with was http://paste.lisp.org/display/88432
>
> But, it executes very slowly.Why so?
>

Your code:

(use 'clojure.contrib.combinatorics)
(apply max (map (fn [[x y]] (* x y)) (filter #(= (seq(str (* (nth %1 0) (
nth %1 1))))(reverse (str (* (nth %1 0) (nth %1 1)))))(selections
(range 100 1000) 2))))

If we outline your steps:
1) generate all pairs of 3 digits numbers
2) multiply (twice), serialize to string (twice), reverse and compare
3) multiply (again)
4) find the max

1) since multiplicationis commutative you don't need to consider both [x y]
and [y x], so you can halve the amount if computation by generating less
pairs
2) put the multiplication and serialization in a let: (fn [[x y]] (let [s
(str (* x y))] (= (seq s) (reverse s))))
3) too bad we can't keep the previous result
4) use reduce instead of apply (except for str and concat)

So fixing #1 and #2 should nearly divide by 4 the run time.

(reduce max
  (map (fn [[x y]] (* x y))
    (filter (fn [[x y]] (let [s (str (* x y))] (= (seq s) (reverse s))))
      (for [x (range 100 1000) y (range x 1000)] [x y]))))

You should notice that we are not interested in pairs but in their product,
so it fixes complaint #3.
(reduce max
  (filter #(let [s (str %)] (= (seq s) (reverse s)))
    (for [x (range 100 1000) y (range x 1000)] (* x y))))

And it's indeed 4x faster.

You can also consider merging the filter in the comprehension:
(reduce max
  (for [x (range 100 1000) y (range x 1000)
        :let [n (* x y) s (str n)]
        :when (= (seq s) (reverse s))]
    n))

(for stylistic reasons)

hth,

Christophe

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to