Guest User

Untitled

a guest
Jan 5th, 2015
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #aho-corasick algorithm
  2. import tables
  3.  
  4. type
  5. AhoNode = object
  6. hit: string
  7. word: bool
  8. to: Table[int, string]
  9. fail: string
  10. failed: bool
  11. type
  12. AhoCorasick* = object
  13. tree*: Table[string, AhoNode]
  14. rootValue: string
  15.  
  16. proc makeNode*(fail: string, failed: bool): AhoNode =
  17. result = AhoNode()
  18. result.hit = ""
  19. result.word = false
  20. result.to = initTable[int, string]()
  21. result.fail = fail
  22. result.failed = failed
  23.  
  24. proc add*(a: var AhoCorasick, s: string) =
  25. ## on first letter .fail goes to root
  26. ## each letter passes path, path = letter + next letter
  27. ## last letter of string is marked .word = true
  28. var current = a.rootValue
  29. for c in s:
  30. let asInt = ord(c)
  31. let path = current & c
  32. #let wordFlag = path == s ? isWord : isNotAWord
  33.  
  34. if a.tree[current].to.hasKey(asInt) == false:
  35. a.tree[current].to[asInt] = path
  36.  
  37. if current == a.rootValue:
  38. a.tree[path] = makeNode(a.rootValue, true)
  39. else:
  40. a.tree[path] = makeNode(a.rootValue, false)
  41.  
  42. current = path
  43.  
  44. a.tree[s].word = true
  45.  
  46.  
  47.  
  48. proc initialize*(a: var AhoCorasick) =
  49. ## adds root node, as first/only letter
  50. ## .fail points to itself and .word is false
  51. a.tree = initTable[string, AhoNode]()
  52. a.tree[""] = makeNode(a.rootValue, true)
  53.  
  54. when isMainModule:
  55. var aho = AhoCorasick(rootValue: "")
  56. aho.initialize()
  57. aho.add("The")
  58.  
  59. echo ($aho)
Advertisement
Add Comment
Please, Sign In to add comment