Advertisement
alestane

Dictionary tree (confirm final)

Feb 3rd, 2014
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local dictionary = {}
  2.  
  3. local function insertWord(dict, word)
  4.     local head, tail = word:upper():match('^(%a)(%a*)$')
  5.     if not head then return false; end
  6.     if not dict[head] then dict[head] = {}; end
  7.     if tail == '' then
  8.         dict[head][''] = true
  9.         return true
  10.     else
  11.         return insertWord(dict[head], tail)
  12.     end
  13. end
  14.  
  15. local function confirmWord(dict, word)
  16.     local head, tail = word:upper():match('^(%a)(%a*)$')
  17.     if not head then return false; end
  18.     if dict[head] then
  19.         if tail == '' then
  20.             return dict[head][''] or false
  21.         else
  22.             return confirmWord(dict[head], tail)
  23.         end
  24.     else
  25.         return false
  26.     end
  27. end
  28.  
  29. insertWord(dictionary, 'BAG')
  30.  
  31. print(confirmWord(dictionary, 'BAG'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement