-
Notifications
You must be signed in to change notification settings - Fork 254
/
largest_series_product.rb
42 lines (38 loc) · 1.1 KB
/
largest_series_product.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# problem: https://exercism.org/tracks/ruby/exercises/largest-series-product
# Solution(idiomatic ruby- using each_cons)
class Series
def initialize(series)
@series = series
end
def largest_product(span)
raise ArgumentError if span<=0 or span>@series.length or !@series.scan(/\D/).empty?
max_product =0
@series.chars.each_cons(span) do |number|
curr_product = 1
number.each do |digit|
curr_product*=digit.to_i
end
max_product = max_product >curr_product ? max_product : curr_product
end
max_product
end
end
# Solution
class Series
def initialize(series)
@series = series
end
def largest_product(span)
raise ArgumentError if span<=0 or span>@series.length or !@series.scan(/\D/).empty?
max_product =0
curr_product = 1
for i in 0..(@series.length-span)
@series[i...(span+i)].chars.each do |digit|
curr_product*= digit.to_i
end
max_product = max_product>curr_product ? max_product: curr_product
curr_product = 1
end
max_product
end
end