Skip to content

Instantly share code, notes, and snippets.

@jondanao
Created June 17, 2011 12:17
Show Gist options
  • Save jondanao/1031305 to your computer and use it in GitHub Desktop.
Save jondanao/1031305 to your computer and use it in GitHub Desktop.
Trie (Lua)
-- Copyright (C) 2010 Danao.org. All Rights Reserved.
-- Jon Danao | jondanao@yahoo.com | http://danao.org
module(..., package.seeall)
function createTrie()
-- PRIVATE
local trie = {}
function addNode(word, position, node, wordLength)
local char = string.sub(word, position, position)
local child = node[char]
if child == nil then
child = {isWord = false}
node[char] = child
end
if position < wordLength then
addNode(word, position + 1, child, wordLength)
elseif position == wordLength then
child.isWord = true
elseif position == wordLength + 1 then
return
end
end
-- PUBLIC
function trie:addWord(word)
local char = string.sub(word, 1, 1)
local rootNode = trie[char]
if rootNode == nil then
rootNode = {isWord = false}
trie[char] = rootNode
end
addNode(word, 2, rootNode, string.len(word))
end
function trie:isWord(word)
local node = trie
for i = 1, string.len(word) do
local char = string.sub(word, i, i)
if node[char] == nil then
return false
else
node = node[char]
end
end
if node.isWord then
return true
else
return false
end
end
function trie:isPrefix(prefix)
local node = trie
local isPrefix = false
for i = 1, string.len(prefix) do
local char = string.sub(prefix, i, i)
node = node[char]
if node ~= nil then
isPrefix = true
else
isPrefix = false
end
end
return isPrefix
end
-- RETURN
return trie
end
@dafwilli
Copy link

dafwilli commented Aug 2, 2011

forget it... typo.... addWord, not addword!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment