Reputation: 909
I have two strings, a
and b
, in Ruby.
a="scar"
b="cars"
What is the easiest way in Ruby to find whether a
and b
contain the same characters?
UPDATE
I am building an Anagram game ,so scar is an anagram of cars.So i want a way to compare a and b and come to conclusion that its an anagram
So c="carcass"
should not be a match
Upvotes: 2
Views: 6266
Reputation: 118271
What is the easiest way in Ruby to find whether a and b contain the same characters?
As per the definitions of Anagram the below written code should work :
a="scar"
b="cars"
a.size == b.size && a.delete(b).empty?
Upvotes: 3
Reputation: 4847
Just for testing arrays vs string vs delete comparation. Assuming we compare strings with equal length.
In the real anagram search you need to sort first word a
once. And then compare it to bunch of b's.
a="scar"
b="cars"
require 'benchmark'
n = 1000000
Benchmark.bm do |x|
x.report('string') { a = a.chars.sort.join; n.times do ; a == b.chars.sort.join ; end }
x.report('arrays') { a = a.chars.sort; n.times do ; a == b.chars.sort ; end }
end
The result:
user system total real
string 6.030000 0.010000 6.040000 ( 6.061088)
arrays 6.420000 0.010000 6.430000 ( 6.473158)
But, if you sort a
each time (for delete
we don't need to sort any word):
x.report('string') { n.times do ; a.chars.sort.join == b.chars.sort.join ; end }
x.report('arrays') { n.times do ; a.chars.sort == b.chars.sort ; end }
x.report('delete') { n.times do ; a.delete(b).empty? ; end }
The result is:
user system total real
string 11.800000 0.020000 11.820000 ( 11.989071)
arrays 11.210000 0.020000 11.230000 ( 11.263627)
delete 1.680000 0.000000 1.680000 ( 1.673979)
Upvotes: 9
Reputation: 19228
You could do like this:
a = 'scar'
b = 'cars'
a.chars.sort == b.chars.sort
# => true
a = 'cars'
b = 'carcass'
a.chars.sort == b.chars.sort
# => false
Upvotes: 11
Reputation: 3881
require 'set'
Set.new(a.chars) == Set.new(b.chars)
updated to take into account comment from sawa
Upvotes: 1