Created
July 3, 2013 07:48
-
-
Save maxjacobson/5916168 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PalindromeFactors | |
attr_accessor :value, :factors | |
def initialize(num1, num2) | |
@value = num1 * num2 | |
@factors = [[num1, num2]] | |
end | |
def add_factor(num1, num2) | |
@factors << [num1, num2] unless @factors.include? [num2, num1] | |
end | |
end | |
class Palindromes | |
def initialize(options) | |
max = options[:max_factor] | |
min = options[:min_factor] || 1 | |
@range = min..max | |
@palindrome_factors = [] | |
end | |
def is_palindrome?(num) | |
num.to_s == num.to_s.reverse | |
end | |
def generate | |
@range.each do |num1| | |
@range.each do |num2| | |
product = num1 * num2 | |
if is_palindrome?(product) | |
already_found = @palindrome_factors.find{ |pf| pf.value == product } | |
if already_found | |
already_found.add_factor(num1, num2) | |
else | |
@palindrome_factors << PalindromeFactors.new(num1, num2) | |
end | |
end | |
end | |
end | |
end | |
def largest | |
@palindrome_factors.sort_by{ |pf| pf.value }.last | |
end | |
def smallest | |
@palindrome_factors.sort_by{ |pf| pf.value }.first | |
end | |
end | |
####### tests ########### | |
require 'fis/test' | |
extend Fis::Test | |
test 'largest_palindrome_from_single_digit_factors' do | |
palindromes = Palindromes.new(max_factor: 9) | |
palindromes.generate | |
largest = palindromes.largest | |
assert_equal 9, largest.value | |
assert [[[3, 3], [1, 9]], [[1, 9], [3, 3]]].include? largest.factors | |
end | |
test 'largest_palindrome_from_double_digit_factors' do | |
palindromes = Palindromes.new(max_factor: 99, min_factor: 10) | |
palindromes.generate | |
largest = palindromes.largest | |
assert_equal 9009, largest.value | |
assert_equal [[91, 99]], largest.factors | |
end | |
test 'smallest_palindrome_from_double_digit_factors' do | |
palindromes = Palindromes.new(max_factor: 99, min_factor: 10) | |
palindromes.generate | |
smallest = palindromes.smallest | |
assert_equal 121, smallest.value | |
assert_equal [[11, 11]], smallest.factors | |
end | |
test 'largest_palindrome_from_triple_digit_factors' do | |
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) | |
palindromes.generate | |
largest = palindromes.largest | |
assert_equal 906609, largest.value | |
assert_equal [[913, 993]], largest.factors | |
end | |
test 'smallest_palindrome_from_triple_digit_factors' do | |
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) | |
palindromes.generate | |
smallest = palindromes.smallest | |
assert_equal 10201, smallest.value | |
assert_equal [[101, 101]], smallest.factors | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment