Sha256: 539b8b9c851cdf5095b701a84adc99093721645cabda24e12eacc026cd698ff3

Contents?: true

Size: 1.09 KB

Versions: 157

Compression:

Stored size: 1.09 KB

Contents

# see also https://gist.github.com/blairand/5237976
# see also https://gist.github.com/burtlo/89b0b817fdccf6bdf20f
module BookKeeping
  VERSION = 2
end

class Series
  attr_reader :digits
  def initialize(numeric_string)
    @digits = numeric_string
  end

  def largest_product(length)
    @length = length
    validate_length
    return 1 if @digits.empty?
    collection_of_digits
    select_max { reduce_to_product  { validate  { separate } } }
  end

  private

  def validate_length
    @length < 0 and
      fail(ArgumentError.new 'Length must be non-negative')
    @length > digits.length and
      fail(ArgumentError.new 'Not enough digits')
  end

  def validate
    yield.take_while { |array| array.size == @length }
  end

  def reduce_to_product
    yield.map { |array| array.inject(1, :*) }
  end

  def select_max
    yield.max
  end

  def separate
    digits.map.with_index do |_, index|
      digits[index, @length]
    end
  end

  def collection_of_digits
    @digits !~ /^\d*$/ and
      fail(ArgumentError.new 'String must contain only digits')
    @digits = digits.chars.map(&:to_i)
  end
end

Version data entries

157 entries across 157 versions & 1 rubygems

Version Path
trackler-2.1.0.1 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.1.0.0 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.55 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.54 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.53 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.52 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.51 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.50 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.49 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.48 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.47 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.46 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.45 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.44 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.43 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.42 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.41 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.40 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.39 tracks/ruby/exercises/largest-series-product/example.rb
trackler-2.0.8.38 tracks/ruby/exercises/largest-series-product/example.rb