Skip to content

Commit 8dcb13e

Browse files
Added consecutive-strings.rb
1 parent 9535af3 commit 8dcb13e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

ruby/6kyu/consecutive-strings.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
=begin
2+
Codewars. 30/04/20. 'Consecutive strings'. 6kyu. Here we create a method that
3+
takes an array of strings and returns the longest possible string that can be
4+
derived by combining k consecutive strings in the array. In the case of there
5+
being multiple matches, return the first. If the array is empty, or k is greater
6+
than the array length, or k is less than 1, return an empty string. Here is the
7+
solution I developed to solve the challenge.
8+
1) We define our method longest_k_consec_ms, which takes 2 arguments, arr, an
9+
array of strings, and k, the amount of consecutive strings that the longest
10+
possible string should consist of.
11+
2) We handle our error checking and return an empty string if the array is
12+
empty, or k is less than 1, or k is greater than the array size.
13+
3) We call the each_cons method with k passed in as its argument, so now we
14+
have an array of arrays where each sub-array is k consecutive strings from
15+
the original array.
16+
4) We map over the array of arrays and join each sub-array. So now we have an
17+
array of combined k-consecutive strings.
18+
5) We call the max_by method with the length method passed in as an argument,
19+
which returns longest (combined k-consecutive) string. If there are more
20+
than 1 string with the max value, the first is returned.
21+
=end
22+
23+
def longest_k_consec_ms(arr, k)
24+
return "" if arr.empty? || k < 1 || k > arr.size
25+
arr.each_cons(k).map(&:join).max_by(&:length)
26+
end

0 commit comments

Comments
 (0)