Project-Euler Ruby

What is Project Euler

Project Euler is a website with a collection of programming and mathematical problems. Each challenge varies in difficulty and there are over 600 challenges. I highly recommend anyone interested in puzzles and programming to create an account and start solving. About Project Euler

** Stop here if you have not yet tried and solved Problem 4. **

**

**

**

**

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.

class Problem4
  require 'benchmark'

  def question
    "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."
  end

  def select_largest_palindrome(list = [])
    list = list.sort
    max = nil

    while(max.nil? && !list.empty?) do
      n = list.pop
      max = n if n.to_s == n.to_s.reverse
    end

    max
  end

  def find_largest_palindrome_product
    pairs = (100..999).to_a.product((100..999).to_a)
    products = pairs.map { |pair| pair[0] * pair[1] }

    select_largest_palindrome(products)
  end

  def solve
    find_largest_palindrome_product
  end

  def benchmark
    Benchmark.measure { solve }
  end

  def correct?
    solve === answer
  end

  private

  def answer
    906609
  end
end

 

Did you like this article? Check out these too.


 

Found this useful? Know how it can be improved? Get in touch and share your thoughts at blog@hocnest.com