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}
Use String#count:
irb(main):001:0> "hello".count("hallo")
=> 4
irb(main):002:0> "abc".count("ab")
=> 2
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
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