patternrubyMinor
Find the letter 'z' within three characters after an 'a'
Viewed 0 times
threeafterthewithincharactersfindletter
Problem
It works, just feel that my solution is too complicated.
# Write a method that takes a string in and returns true if the letter
# "z" appears within three letters **after** an "a". You may assume
# that the string contains only lowercase letters.
#
# Difficulty: medium.
def nearby_az(string)
i = 0
while i < string.length
if string[i] == "a"
a_index = i
end
if string[i] == "z"
z_index = i
end
if (a_index) && (z_index) && (a_index < z_index) && ((z_index - a_index) <= 3)
return true
end
i += 1
end
return false
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts('nearby_az("baz") == true: ' + (nearby_az('baz') == true).to_s)
puts('nearby_az("abz") == true: ' + (nearby_az('abz') == true).to_s)
puts('nearby_az("abcz") == true: ' + (nearby_az('abcz') == true).to_s)
puts('nearby_az("a") == false: ' + (nearby_az('a') == false).to_s)
puts('nearby_az("z") == false: ' + (nearby_az('z') == false).to_s)
puts('nearby_az("za") == false: ' + (nearby_az('za') == false).to_s)Solution
Riffing on @Shepmaster's excellent answer:
def nearby_az(string)
!!string.match(/a.{,2}z/)
end
['baz', 'abz', 'abcz'].each do |s|
puts "nearby_az('#{s}') expect true: #{nearby_az(s)}"
end
['a', 'z', 'za'].each do |s|
puts "nearby_az('#{s}') expect false: #{nearby_az(s)}"
endCode Snippets
def nearby_az(string)
!!string.match(/a.{,2}z/)
end
['baz', 'abz', 'abcz'].each do |s|
puts "nearby_az('#{s}') expect true: #{nearby_az(s)}"
end
['a', 'z', 'za'].each do |s|
puts "nearby_az('#{s}') expect false: #{nearby_az(s)}"
endContext
StackExchange Code Review Q#119347, answer score: 4
Revisions (0)
No revisions yet.