jeudi 11 janvier 2018

Get all possible substrings and their count

I'm trying to get all possible substrings and their count in a hash. E.g.

 "abc" => { a: 1, b: 1, ab: 1, bc: 1}

For that I wrote the following code:

 def get_all(b)
     (0..(b.size-1)).to_a.combination(2).inject({}) { |h, g|
        s = b[g[0],g[1]]
        h[s] ? ( h[s] += 1) : ( h[s] = 1 )
        h 
      } 
 end

But somehow It does not work correctly, because for "abchh" It returns:

{"a"=>1, "ab"=>1, "abc"=>1, "abch"=>1, "bc"=>1, "bch"=>1, "bchh"=>1, "chh"=>2, "hh"=>1}

chh is in there twice, but I can't understand why. What do I wrong?

Thank you!

Aucun commentaire:

Enregistrer un commentaire