Created
August 29, 2013 00:54
-
-
Save broguinn/6373144 to your computer and use it in GitHub Desktop.
largest_series_product
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 largest_series_product(number, span_length=3) | |
if number.match(/\D/) | |
raise ArgumentError.new("Numbers only") | |
elsif number.length < span_length | |
raise ArgumentError.new("The number must have at least #{span_length} digits") | |
end | |
product_finder(series_splitter(number, span_length)).max | |
end | |
def series_splitter(number, span_length) | |
ranges = [] | |
(number.length - span_length + 1).times do |i| | |
ranges << number[i, span_length] | |
end | |
ranges | |
end | |
def product_finder(spans) | |
spans.map do |span| | |
span.split("").inject(1) do |product, n| | |
product * n.to_i | |
end | |
end | |
end | |
puts largest_series_product("123456789") |
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 'largest_series_product' | |
describe 'largest_series_product' do | |
it 'returns the product of the digits of a three digit number string' do | |
largest_series_product('256').should eq 60 | |
end | |
it 'rejects any number shorter than 3' do | |
expect { largest_series_product('25') }.to raise_error | |
end | |
it 'rejects any string that contains non-numbers' do | |
expect { largest_series_product('foo525') }.to raise_error | |
expect { largest_series_product('123 123') }.to raise_error | |
expect { largest_series_product('132-4433%') }.to raise_error | |
end | |
it 'returns the highest series product' do | |
largest_series_product("12345").should eq 60 | |
end | |
it 'can take an optional argument of span width' do | |
largest_series_product("12342", 2).should eq 12 | |
end | |
it 'can handle a large string of numbers' do | |
largest_series_product('73167176531330624919225119674426574742355349194934', 6).should eq 23520 | |
end | |
end | |
describe 'series_splitter' do | |
it 'splits a number string into a 3 digit series' do | |
series_splitter("12345", 3).should eq ["123", "234", "345"] | |
end | |
end | |
describe 'product_finder' do | |
it 'returns an array of digit products' do | |
product_finder(["123", "234", "345"]).should eq [6, 24, 60] | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment