Counting the number of times two letters appear together

I am trying to make a Ruby program that counts the number of times two letters appear together. This is what is written in the file I am reading:

hola chau 

And here is what I am trying to get:

 ho;ol;la;ch;ha;au; 1;1;1;1;1;1; 

I can not get it to work correctly. This is my code:

 file = File.read(gets.chomp) todo = file.scan(/[az][az]/).each_with_object(Hash.new(0)) { |a, b| b[a] += 1 } keys = '' values = '' todo.each_key { |key| keys += key + ';' } todo.each_value { |value| values += value.to_s + ';' } puts keys puts values 

This is the result I get:

 ho;la;ch;au; 1;1;1;1; 

Why am I not getting every combination of characters? What should I advertise for my regular expression so that it takes into account each combination of characters?

+6
source share
2 answers

Since characters overlap, you need to use lookahead to capture overlapping characters.

 (?=([az][az])) 

Demo

+9
source

This is one way.

 def char_pairs(str) str.split(/\s+/).flat_map { |w| w.chars.each_cons(2).map(&:join) } .each_with_object({}) { |e,h| h[e] = (h[e] ||= 0 ) + 1 } end char_pairs("hello jello") #=> {"he"=>1, "el"=>2, "ll"=>2, "lo"=>2, "je"=>1} char_pairs("hello yellow jello") #=> {"he"=>1, "el"=>3, "ll"=>3, "lo"=>3, "ye"=>1, "ow"=>1, "je"=>1} 

Having a hash makes it easy to convert it to any output format you want.

+2
source

Source: https://habr.com/ru/post/974652/


All Articles