Skip to content

Instantly share code, notes, and snippets.

@RakibFiha
Last active October 17, 2020 06:27
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 RakibFiha/0942ae5ea4ccc4935662ef394cb06c25 to your computer and use it in GitHub Desktop.
Save RakibFiha/0942ae5ea4ccc4935662ef394cb06c25 to your computer and use it in GitHub Desktop.
Find if a string has unique characters in Lua with Set implementation
#!/usr/bin/env lua
local lib = require "lib"
local totable = lib.totable
local Set = lib.Set
local tablelength = lib.tablelength
local contains = lib.contains
-- isuniqe function implementation
-- print(isuniqe("aabc")) -- would return false
function isuniqe(str)
strtab = totable(str)
return tablelength(Set(strtab)) == string.len(str)
end
if arg[0] == lib.GetCurrentLuaFile() then
-- if arg[0] == 'is_unique.lua' then
print(isuniqe("aabc"))
print(isuniqe("abc"))
end
local lib = {}
-- get current filename
function lib.GetCurrentLuaFile()
local source = debug.getinfo(2, "S").source
if source:sub(1,1) == "@" then
return source:sub(2)
end
end
-- Basic Set Implementation
-- shanda = Set{"1", "2", "3", "a", "a", "b", "c",}
-- print(shanda["1"]) -- would be true
function lib.Set(t)
local set = {}
for _, v in ipairs(t) do set[v] = true end
return set
end
-- Tablefy: convert string to table: returns table address
-- print(tablelength(totable("rakib"))) -- would become {"r","a","k","i","b"}
function lib.totable(str)
local t = {}
for i = 1, #str do t[i] = str:sub(i, i) end
return t
end
-- Get length of Set, table etc
-- print(tablelength(shanda))
function lib.tablelength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
-- Check if element exists in Set
-- print(contains(shanda,"1"))
function lib.contains(set, e)
return set[e]
end
return lib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment