I am trying to make a Ruby program that counts the numer of times two letters appear together. This is what is written in the file I'm reading:
hola
chau
And this is what I'm trying to get:
ho;ol;la;ch;ha;au;
1;1;1;1;1;1;
I can't get it to work properly. This is my code so far:
file = File.read(gets.chomp)
todo = file.scan(/[a-z][a-z]/).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'm getting:
ho;la;ch;au;
1;1;1;1;
Why am I not getting every combination of characters? What should I ad to my regex so it would count every combination of characters?
Because the characters are overlapped, you need to use a lookahead to capture the overlapped characters.
(?=([a-z][a-z]))
DEMO
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 the hash, it is an easy matter to convert it to any output format you desire.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With