Skip to content

Instantly share code, notes, and snippets.

@javierhonduco
Last active January 1, 2016 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javierhonduco/29c323b71e97242467e6 to your computer and use it in GitHub Desktop.
Save javierhonduco/29c323b71e97242467e6 to your computer and use it in GitHub Desktop.
dfa
class Node
attr_accessor :id, :type, :goto
def initialize(type = nil, goto = {})
@type, @goto = type, goto
end
end
def matches?(pattern, text)
first = Node.new
node = first
i = 0
pattern.each_char do |char|
nextnode = Node.new
endnode = Node.new
endnode.type = 'end'
node.id = i
if char == '*'
node.goto[char] = node
else
node.goto[char] = nextnode
end
if i==0
node.type = 'start'
elsif i==pattern.length-1
if char == '*'
node.type = 'end'
else
node.goto[char] = endnode
end
else
node.type = 'transition'
end
if char != '*'
node = nextnode
end
i+=1
end
i = 0
currentstate = first
text.each_char do |char|
currentstate = (currentstate.goto[char] or currentstate.goto['*']) # handle undefined GOTOs
if currentstate and i == text.length-1 and currentstate.type=='end'
return true
end
i+=1
end
return false
end
puts matches?('a**********a', 'aa')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment