Project Euler #4
Did problem #4 today. Find the largest product of 2 three digits that is a palindrome.
This one wasn't too hard (given that I don't know clojure well enough to not have to scour docs for the order of arguments and such). First made a function that just returns all the products of 100...999, (actually 101; no product of 100 * anything can be a palindrome) as a list of 2 item vectors of the product and its palindrome, as strings.
Then ran it through a filter which removed all the non-palindromes. Then a map to get one of the elements of the vector. Then mapped it to an integer. Then applied max to that.
However, I hated that solution.
So, I improved upon it slightly by reversing the range to start from the high point and counting down, thinking that I could generate the palindromes in pre-sorted order, and I could just take the first one. Unfortunately, my plan did not work. But, I did realize how to better use the for comprehension to do the filtering for me, rather than after the fact, so I didn't bother doing as many int -> string -> int conversions, which did make it faster. I also eliminated the function wrapping the for, and just stuck it inline. So what I ended up with is here:
(apply max (for [a (range 1000 101 -1) b (range 1000 a -1)
:when (=
(.toString (* a b))
(apply str (reverse (.toString (* a b)))))] (* a b)))
1 Comments:
Nice, and a lot smaller than mine. I took the approach that the largest possible answer was (* 999 999), then worked backwards from there. Basically, start with that seed, then keep moving backwards through palindromic numbers until I find a match.
Of course, that was one of the first bits of code I wrote in Clojure, so I hadn't even learned (recur) yet. I look at it now and see all kinds of clunky stuff....
https://github.com/ax2groin/clojure/blob/master/euler/euler-004.clj
Post a Comment
Subscribe to Post Comments [Atom]
<< Home