Skip to content

Instantly share code, notes, and snippets.

@joalbertg
Last active May 23, 2022 17:30
Show Gist options
  • Save joalbertg/42044c28a257b84a663d7554c2166e05 to your computer and use it in GitHub Desktop.
Save joalbertg/42044c28a257b84a663d7554c2166e05 to your computer and use it in GitHub Desktop.
challenge: count even substring
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment