Skip to content

Commit 567453b

Browse files
committed
exercism-80 Largest Series Prodcut
1 parent 50f14fa commit 567453b

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
305305
77. [Simple Linked List](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/simple_linked_list.rb)
306306
78. [Binary Search Tree](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/binary_search_tree.rb)
307307
79. [Rotational Cipher](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/rotational_cipher.rb)
308+
80. [Largest Series Product](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/largest_series_product.rb)
308309

309310
<a name="leetcode"/>
310311

exercism/largest_series_product.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# problem: https://exercism.org/tracks/ruby/exercises/largest-series-product
2+
3+
# Solution(idiomatic ruby- using each_cons)
4+
class Series
5+
def initialize(series)
6+
@series = series
7+
end
8+
def largest_product(span)
9+
raise ArgumentError if span<=0 or span>@series.length or !@series.scan(/\D/).empty?
10+
max_product =0
11+
@series.chars.each_cons(span) do |number|
12+
curr_product = 1
13+
number.each do |digit|
14+
curr_product*=digit.to_i
15+
end
16+
max_product = max_product >curr_product ? max_product : curr_product
17+
end
18+
max_product
19+
end
20+
end
21+
22+
# Solution
23+
class Series
24+
def initialize(series)
25+
@series = series
26+
end
27+
28+
def largest_product(span)
29+
raise ArgumentError if span<=0 or span>@series.length or !@series.scan(/\D/).empty?
30+
max_product =0
31+
curr_product = 1
32+
for i in 0..(@series.length-span)
33+
@series[i...(span+i)].chars.each do |digit|
34+
curr_product*= digit.to_i
35+
end
36+
max_product = max_product>curr_product ? max_product: curr_product
37+
curr_product = 1
38+
end
39+
max_product
40+
end
41+
end
42+

0 commit comments

Comments
 (0)