Last active
May 23, 2022 17:30
-
-
Save joalbertg/42044c28a257b84a663d7554c2166e05 to your computer and use it in GitHub Desktop.
challenge: count even substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# quickstart | |
# | |
# ruby count_even_substrings.rb | |
def count_even_substrings(str) | |
j = 0 | |
size = str.size | |
acc = [] | |
loop do | |
i = 1 | |
even_substring({ acc: acc, size: size, str: str, i: i, j: j }) | |
break if j >= (size - 1) | |
j += 1 | |
end | |
acc.any? ? acc.size : -1 | |
end | |
def even_substring(params) | |
loop do | |
substr = params[:str].slice(params[:j], params[:i]) | |
params[:acc] << substr if substr.to_i.even? | |
break if params[:i] > (params[:size] - (params[:j] + 1)) | |
params[:i] += 1 | |
end | |
end | |
p count_even_substrings('56789') # 6 | |
p count_even_substrings('5847548') # 18 | |
p count_even_substrings('5555555') # -1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
6 | |
18 | |
-1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment