Last active
October 17, 2020 06:27
-
-
Save RakibFiha/0942ae5ea4ccc4935662ef394cb06c25 to your computer and use it in GitHub Desktop.
Find if a string has unique characters in Lua with Set implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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