Created
August 30, 2013 00:55
-
-
Save broguinn/6385216 to your computer and use it in GitHub Desktop.
palindrome
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
def palindrome(first_number, second_number=first_number) | |
if first_number > second_number | |
raise ArgumentError.new 'First number cannot be greater than second number' | |
end | |
palindromes = [] | |
(first_number..second_number).each do |number| | |
(first_number..second_number).each do |number2| | |
product = number * number2 | |
if product.to_s.split("") == product.to_s.split("").reverse && !(palindromes.include?(product)) | |
palindromes << product | |
end | |
end | |
end | |
palindromes.sort | |
end |
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 'rspec' | |
require 'palindrome' | |
describe 'palindrome' do | |
it 'raises an exception for non-number data' do | |
expect {palindrome(1, 'foo')}.to raise_exception | |
expect {palindrome(1, [])}.to raise_exception | |
expect {palindrome(true, 'foo')}.to raise_exception | |
end | |
it 'raises an exception if the first argument is greater than the second' do | |
expect {palindrome(3, 2)}.to raise_exception | |
end | |
it 'finds palindromes for a basic range' do | |
palindrome(10, 12).should eq [121] | |
end | |
it 'doesn\'t repeat matches' do | |
palindrome(2, 11).should eq [4, 6, 8, 9, 22, 33, 44, 55, 66, 77, 88, 99, 121] | |
end | |
it 'returns an ordered array' do | |
palindrome(2, 4).should eq [4, 6, 8, 9] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment