ruby - Delete from where? -


below have written piece of code that's supposed count number of occurrences of characters in string , display result in hash. idea rid of letter in string right after i've counted don't put hash more once.

my original code this:

def letter_count_spec(str) letter_count = hash.new #create hash letter = str.split('') #separate letters letter.each{ |e|     if( /[a-za-z0-9]/.match(e)  )         occurances = letter.count{ |x| x==e}         letter_count[e] = occurances         letter.delete(e) #delete letter       end }          return letter_count end  letter_count_spec("cat") 

result: => {"c"=>1, "t"=>1}

i lose "a"!

so tried this:

def letter_count_spec(str) letter_count = hash.new #create hash letter = str.split('') #separate letters letter.each{ |e|     if( /[a-za-z0-9]/.match(e)  )         occurances = letter.count{ |x| x==e}         letter_count[e] = occurances     end }         letter.each{ |e|     letter.delete(e) #delete letter }     return letter_count end  letter_count_spec("cat") 

result => {"a"=>1, "c"=>1, "t"=>1}

why need go through array again delete?

the modification of collection during iteration may cause problems, stated in comment.

the word counting algorithm involves hash keep track of word count, , iterator go through content. don't need modify original collection. o(n) solution, given hash has o(1) complexity on update in general case. however, count , delete approach in post has o(n^2) complexity (if works).

def letter_count_spec(str)   letter_count = hash.new(0) # create hash, , use 0 default value   letter = str.split('')     # separate letters   letter.each |e|     if /[a-za-z0-9]/.match(e)       letter_count[e] += 1   # increment count     end   end   letter_count end 

btw, in ruby, it's convention use do ... end multiple lines block, unless {} required in circumstances.


Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -