ruby - Take in string, return true if after "a", a "z" appears within three places -


# write method takes string in , returns true if letter # "z" appears within 3 letters **after** "a". may assume # string contains lowercase letters.  

i came this, seems logical, reason if "z" comes directly after "a", returns false. can explain why?

    def nearby_az(string)         = 0         if string[i] == "a" && string[i+1] == "z"             return true         elsif string[i] == "a" && string[i+2] == "z"             return true         elsif string[i] == "a" && string[i+3] == "z"             return true         else return false          end         += 1     end 

@shivram has given reason problem. here couple of ways it.

problem tailor-made regular expression

r = /          # match "a"     .{,2} # match n characters 0 <= n <= 2     z      # match "z"     /x     # extended/free-spacing regex definition mode  !!("wwwaeezdddddd" =~ r)  #=> true !!("wwwaeeezdddddd" =~ r) #=> false 

you see regular expression written

/a.{0,2}z/ 

but extended mode allows document each of elements. that's not important here useful when regex complex.

the ruby trick !!

!! used convert truthy values (all false , nil) true , falsy values (false or nil) false:

!!("wwwaeezdddddd" =~ r)   #=> !(!("wwwaeezdddddd" =~ r))   #=> !(!3)   #=> !false   #=> true  !!("wwwaeezdddddd" =~ r)   #=> !(!("wwwaeeezdddddd" =~ r))   #=> !(!nil)   #=> !true   #=> false 

but !! not necessary, since

puts "hi" if 3   #=> "hi" puts "hi" if nil #=> 

some don't !!, arguing that

<condition> ? true : false 

is more clear.

a non-regex solution

def z_within_4_of_a?(str)   (str.size-3).times.find { |i| str[i]=="a" && str[i+1,3].include?("z") } ? true : false end  z_within_4_of_a?("wwwaeezdddddd")   #=> true z_within_4_of_a?("wwwaeeezdddddd")   #=> false 

this uses methods fixnum#times, enumerable#find , string#include? (and string#size of course).


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -