Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate number of chars common to two strings?

Tags:

ruby

How would you calculate the intersection of characters between two strings?

For example (assuming we would have a method called String.intersection):

"abc".intersection("ab") = 2
"hello".intersection("hallo") = 4

Ok, boys and girls, thanks for your massive feedback. Some more examples:

"aaa".intersection("a") = 1
"foo".intersection("bar") = 0
"abc".intersection("bc") = 2
"abc".intersection("ac") = 2
"abba".intersection("aa") = 2

Some more notes: Wikipedia defines intersection as follows:

Intersection of the sets A and B, denoted A ∩ B, is the set of all objects that are members of both A and B. The intersection of {1, 2, 3} and {2, 3, 4} is the set {2, 3}

like image 649
auralbee Avatar asked May 20 '11 14:05

auralbee


2 Answers

Use String#count:

irb(main):001:0> "hello".count("hallo")
=> 4
irb(main):002:0> "abc".count("ab")
=> 2
like image 188
Vasiliy Ermolovich Avatar answered Oct 11 '22 14:10

Vasiliy Ermolovich


This passes all your described test cases:

class String
  def intersection(other)
    str = self.dup
    other.split(//).inject(0) do |sum, char|
      sum += 1 if str.sub!(char,'')
      sum
    end
  end
end
like image 44
Michael Kohl Avatar answered Oct 11 '22 13:10

Michael Kohl