Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Counting chars in a sequence not using regex

Need help with this code on counting chars in a sequence.

This is what I want:

word("aaabbcbbaaa") == [["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
word("aaaaaaaaaa") == [["a", 10]]
word("") == []

Here is my code:

def word(str)
words=str.split("")
count = Hash.new(0)

words.map {|char| count[char] +=1 }

return count
end

I got word("aaabbcbbaaa") => [["a", 6], ["b", 4], ["c", 1]], which is not what I want. I want to count each sequence. I prefer a none regex solution. Thanks.

like image 377
hken27 Avatar asked Dec 12 '22 09:12

hken27


1 Answers

Split string by chars, then group chunks by char, then count chars in chunks:

def word str
  str
  .chars
  .chunk{ |e| e }
  .map{|(e,ar)| [e, ar.length] }
end

p word "aaabbcbbaaa"
p word("aaaaaaaaaa")
p word ""

Result:

[["a", 3], ["b", 2], ["c", 1], ["b", 2], ["a", 3]]
[["a", 10]]
[]
like image 57
Yevgeniy Anfilofyev Avatar answered Dec 14 '22 23:12

Yevgeniy Anfilofyev