-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_for_anagram.rb
More file actions
57 lines (42 loc) · 1.08 KB
/
check_for_anagram.rb
File metadata and controls
57 lines (42 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require 'minitest/autorun'
class TestCheckForAnagram < Minitest::Test
def test_check_for_anagram_sub
assert_equal true, check_for_anagram_sub("geeks", "kseeg")
assert_equal false, check_for_anagram_sub("allergy", "allergyy")
end
def test_check_for_anagram_eql
assert_equal true, check_for_anagram_eql("geeks", "kseeg")
assert_equal false, check_for_anagram_eql("allergy", "allergyy")
end
end
def check_for_anagram_sub(s1, s2)
farr = Array.new(26){0}
s1.chars.each do |s|
farr[s.ord - 'a'.ord] += 1
end
s2.chars.each do |s|
farr[s.ord - 'a'.ord] -= 1
end
farr.each do |f|
return false if f != 0
end
true
end
def check_for_anagram_eql(s1, s2)
farr = Array.new(26){0}
s1.chars.each do |s|
farr[s.ord - 'a'.ord] += 1
end
s1h = farr.join
farr = Array.new(26){0}
s2.chars.each do |s|
farr[s.ord - 'a'.ord] += 1
end
s2h = farr.join
s1h == s2h
end
require 'benchmark'
Benchmark.bm do |x|
x.report(:eql) { check_for_anagram_eql("abc"*1000, "abc"*1000) }
x.report(:sub) { check_for_anagram_sub("abc"*1000, "abc"*1000) }
end