Skip to content

Instantly share code, notes, and snippets.

@tcmacdonald
Created November 9, 2018 20:36
Show Gist options
  • Save tcmacdonald/ab1f5a237048d8c0e32b0a62a39d3abd to your computer and use it in GitHub Desktop.
Save tcmacdonald/ab1f5a237048d8c0e32b0a62a39d3abd to your computer and use it in GitHub Desktop.
Coding Challenge #2
def question_marks(str)
# Get any number + chars + number pattern...
regex = /(\d)[a-zA-Z\?]*(\d)/
# Iterate over each occurrence and return the MatchData object
matches = str.to_enum(:scan, regex).map { Regexp.last_match }
# Iterate over each match and return a boolean meeting the following conditions...
bools = matches.collect do |match|
# Do the numbers at the beginning and end of the string add up to 10?
if match[1].to_i + match[2].to_i == 10
# Are there exactly 3 question marks within the string?
match.to_s.scan(/\?/).count == 3
end
end.compact # .compact removes any nil entries
# Evaluate if all items in our array are true and return the result
!bools.empty? && bools.all?
end
# ---------------------------------------- //
str = "arrb6???4xxbl5???eee5"
puts "#{str}: #{question_marks(str)}" # true
str = "aa6?9"
puts "#{str}: #{question_marks(str)}" # false
str = "acc?7??sss?3rr1??????5"
puts "#{str}: #{question_marks(str)}" # true
str = "dk7???3j??hk8???2jd?k?sj?hfkj"
puts "#{str}: #{question_marks(str)}" # true
str = "dk7??3j??hk8???2jd?k?sj?hfkj"
puts "#{str}: #{question_marks(str)}" # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment