I like that problem. I've come up with a solution (starting from
yours) that I like a bit more anyway. I should rewrite it using the
new reducers framework. ;-)
As with most of the Euler problems there is probably some mathematical
shortcut you can use that does 1/1x10^6 of the work for the same
result. This was a fun thing to write though.
Here is mine:
;; stolen from you, it could use a zero? check as well
(defn collatz [n]
(if (even? n)
(/ n 2)
(inc (* 3 n))))
;; Use loop and recur so we don't blow the stack with big numbers
(defn collatz-seq [start]
(loop [s start ls []]
(let [next-number (collatz s)]
(if (= s 1)
(conj ls 1)
(recur next-number (conj ls s))))))
;; we can use reduce here as we are only trying to get the largest
sequence rather than all of the sequences. We can throw the rest away.
(defn max-collatz [start end]
(reduce
(fn [mx new]
(let [new-count (count (collatz-seq new))]
(if (> new-count (:count mx)) {:num new :count new-count} mx)))
{:num 0 :count 0}
(range start end)))
;; the result
;; user> (:num (max-collatz 1 1000000))
;; 837799
;; The sequence length is 525
Does this sound about right to you?
cheers,
Bruce
> --
> You received this message because you are subscribed to the Google Groups
> "London Clojurians" group.
> To view this discussion on the web visit
>
https://groups.google.com/d/msg/london-clojurians/-/YrrtnbMoaCUJ.
> To post to this group, send email to
london-c...@googlegroups.com.
> To unsubscribe from this group, send email to
>
london-clojuri...@googlegroups.com.
> For more options, visit this group at
>
http://groups.google.com/group/london-clojurians?hl=en.
--
CTO & co-founder
@MastodonC
mastodonc.com