Contract Work

Thursday, October 17, 2013

Euler 4! Onwards and upwards!

As I talk about doing these Project Euler problems, I increasingly realize how much they helped me crystalize certain concepts in the last few weeks. I knew they were helping me solidify some coding skills, but honestly, I wasn't sure if spending time on these was a waste of time and if I should have just continued to build things instead. One originally unseen benefit of having these problems done is being able to use them as a template to identify other things. For example, I solved my eulers by testing in rsepc and writing in ruby. The past few weeks, I've had more conversations about other testing languages including cucumber and minitest. I read about them first, but then I've searched for other people who have solved eulers and tested first using these different test suites. Because I'm familiar with the problem, I'm more easily able to identify with the example and look at how they wrote their tests.
Now, onto Problem 4.
A palindromic number reads the same both ways. The largest palindrome 
made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

First the tests:
require 'problem4/problem4'


describe "largest palindrome" do        

 it "finds the largest palindrome of 2 digit numbers" do
   expect(Problem4.answer(10...100)).to eq 9009
 end

 it "finds the largest palendrome of 3 digit numbers" do
   expect(Problem4.answer(100...1000)).to eq 906609
 end
end

Now for the solution code:
module Problem4

def self.answer(largest_palindrome_range)
  max = 0
  (largest_palindrome_range).each do |a|
    (a...largest_palindrome_range.end).each do |b|
       product = a*b
    max = [max, product].max if product.to_s == product.to_s.reverse
    end
  end
  return max
end

puts Problem4.answer(100...1000)
end

So, first, I thought about a palindrome. A palindrome is the reverse of itself. So, I took the range we were testing and took each number to get a and then did the same from a to the end of the range to get b. Then I multiplied all of the resulting 2 number possibilities. Finally, in order to find the maximum, you take the product, convert it to a string and then see if it equals the reverse of the string.

This one was really tough for me. I knew about how to find the max and I knew how to check if it was a palindrome and reversing the string, but the middle section of finding the products via the range given was pretty challenging for me to wrap my head around.

No comments:

Post a Comment