-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubstring.rb
More file actions
73 lines (58 loc) · 1.57 KB
/
substring.rb
File metadata and controls
73 lines (58 loc) · 1.57 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
require 'byebug'
str = 'redbluegreengreenblue'
ptn = 'abccb'
str2 = 'redblueredblue'
ptn2 = 'abab'
def genRegex pt
pt.chars.inject('') {|acc, c| acc + '(\w{%d})'}
end
def baseK (k, n)
n == 0 ? [] : baseK(k, (n/k)) << n % k
end
def innerProd (ary, bry)
ary.zip(bry).inject(0) {|acc, bs| acc += bs.inject(1, :*)}
end
def counts (ary)
if ary == [] ; [] else
hh, tt = ary.partition {|a| a == ary[0]}
counts(tt).unshift(hh.length)
end
end
def allValid (ptn, str)
ptns = ptn.split('') # tokenize pattern
ps = ptns.uniq.length # number of unique tokens
poly = counts ptns # number of token multiplicities
strL = str.length # initializes string length lookup
wordLenRange = strL ** (ps-1)...strL ** ps
wordLenRange.inject([]) do |acc, i|
vs = baseK(strL, i) # n-ary reps
# no empty patterns && solves polynomial at string length
cond = vs.all? {|t| t > 0} && innerProd(poly, vs) == strL
cond ? acc << vs : acc
end
end
def splittings (ptn, str)
ptnU = ptn.split('').uniq
allValid(ptn, str).map do |kv|
ary = ptnU.zip(kv).inject(ptn) do |pt, (pu, v)|
pt = pt.gsub(pu, v.to_s)
end.split('').map(&:to_i)
str.match(genRegex(ptn) % ary)[1..ptn.length]
end
end
def hasPattern? (ptn, str)
ptV = splittings(ptn,str).any? do |ss|
ss, pt = ss.uniq, ptn
while !(pt.nil? || pt.empty?)
pt = pt.delete(pt[0])
ss.shift
end
pt.length == ss.length
end
result = ptV ? "Has Pattern\n" : "Fails Pattern\n"
print result
end
hasPattern?(ptn,str)
hasPattern?(ptn2, str2)
hasPattern?(ptn2, str)
hasPattern?(ptn, str2)