Skip to content

Instantly share code, notes, and snippets.

@dustinbrownman
Last active December 21, 2015 23:09
Show Gist options
  • Select an option

  • Save dustinbrownman/6380408 to your computer and use it in GitHub Desktop.

Select an option

Save dustinbrownman/6380408 to your computer and use it in GitHub Desktop.
Returns the highest product from a string of numbers for the given series length (defaulted to 3). For example, the string "123456789" with a series length of 3 returns 504 (7 * 8 * 9). If I adjust the series length to 4, it returns 3024 (6 * 7 * 8 * 9).
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
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