/
ch-2.rb
executable file
·55 lines (47 loc) · 971 Bytes
/
ch-2.rb
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
#! /usr/bin/ruby
def str2hash(a)
m = Hash.new(0)
a.split('').each do |c|
if c.match(/[[:alpha:]]/) then
m[c.downcase] += 1
end
end
return m
end
def completingword(a, cw)
ah = str2hash(a)
out = []
cw.each do |t|
valid = true
th = str2hash(t)
ah.each do |k, v|
if !th.has_key?(k) then
valid = false
break
end
if th[k] < v then
valid = false
break
end
end
if valid then
out.push(t)
end
end
if out.length == 0 then
return ""
end
return out.sort_by { |x| x.length }[0]
end
require 'test/unit'
class TestCompletingword < Test::Unit::TestCase
def test_ex1
assert_equal('accbbb', completingword('aBc 11c', ['accbbb', 'abc', 'abbc']))
end
def test_ex2
assert_equal('baacl', completingword('La1 abc', ['abcl', 'baacl', 'abaalc']))
end
def test_ex3
assert_equal('bjb', completingword('JB 007', ['jj', 'bb', 'bjb']))
end
end