Last active
March 5, 2016 00:16
-
-
Save durrellchamorro/ed61d398a8d931f20183 to your computer and use it in GitHub Desktop.
Palindrome Products
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
require 'pry' | |
class Palindromes | |
attr_accessor :min_factor, :max_factor, :palindrome_factors, :palindromes | |
def initialize(min_factor: 1, max_factor: 1) | |
@min_factor, @max_factor = min_factor, max_factor | |
end | |
def generate | |
@palindrome_factors = all_factor_combinations.select do |combination| | |
product = combination[0] * combination[1] | |
product.to_s == product.to_s.reverse | |
end | |
@palindromes = @palindrome_factors.map do |pair_of_factors| | |
pair_of_factors[0] * pair_of_factors[1] | |
end | |
end | |
def all_factor_combinations | |
range = @min_factor.upto(@max_factor).to_a | |
range.product(range.reverse) | |
end | |
def largest | |
factors_for_largest_palindrome = @palindrome_factors.select do |pair_of_factors| | |
pair_of_factors[0] * pair_of_factors[1] == @palindromes.max | |
end | |
Palindrome.new(@palindromes.max, factors_for_largest_palindrome) | |
end | |
def smallest | |
factors_for_smallest_palindrome = @palindrome_factors.select do |pair_of_factors| | |
pair_of_factors[0] * pair_of_factors[1] == @palindromes.min | |
end | |
Palindrome.new(@palindromes.min, factors_for_smallest_palindrome) | |
end | |
end | |
class Palindrome | |
attr_accessor :value, :largest_or_smallest_factors | |
def initialize(value, largest_or_smallest_factors) | |
@value = value | |
@largest_or_smallest_factors = largest_or_smallest_factors | |
end | |
def factors | |
@largest_or_smallest_factors | |
end | |
end | |
palindromes = Palindromes.new(max_factor: 9) | |
palindromes.generate | |
largest = palindromes.largest | |
p largest.value | |
p largest.factors | |
palindromes = Palindromes.new(max_factor: 99, min_factor: 10) | |
palindromes.generate | |
largest = palindromes.largest | |
p largest.value | |
p largest.factors | |
palindromes = Palindromes.new(max_factor: 99, min_factor: 10) | |
palindromes.generate | |
smallest = palindromes.smallest | |
p smallest.value | |
p smallest.factors | |
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) | |
palindromes.generate | |
largest = palindromes.largest | |
p largest.value | |
p largest.factors | |
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) | |
palindromes.generate | |
smallest = palindromes.smallest | |
p smallest.value | |
p smallest.factors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment