Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
30
Task/Caesar-cipher/Lua/caesar-cipher-1.lua
Normal file
30
Task/Caesar-cipher/Lua/caesar-cipher-1.lua
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
local function encrypt(text, key)
|
||||
return text:gsub("%a", function(t)
|
||||
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
|
||||
|
||||
local r = t:byte() - base
|
||||
r = r + key
|
||||
r = r%26 -- works correctly even if r is negative
|
||||
r = r + base
|
||||
return string.char(r)
|
||||
end)
|
||||
end
|
||||
|
||||
local function decrypt(text, key)
|
||||
return encrypt(text, -key)
|
||||
end
|
||||
|
||||
caesar = {
|
||||
encrypt = encrypt,
|
||||
decrypt = decrypt,
|
||||
}
|
||||
|
||||
-- test
|
||||
do
|
||||
local text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
|
||||
local encrypted = caesar.encrypt(text, 7)
|
||||
local decrypted = caesar.decrypt(encrypted, 7)
|
||||
print("Original text: ", text)
|
||||
print("Encrypted text: ", encrypted)
|
||||
print("Decrypted text: ", decrypted)
|
||||
end
|
||||
32
Task/Caesar-cipher/Lua/caesar-cipher-2.lua
Normal file
32
Task/Caesar-cipher/Lua/caesar-cipher-2.lua
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
local memo = {}
|
||||
|
||||
local function make_table(k)
|
||||
local t = {}
|
||||
local a, A = ('a'):byte(), ('A'):byte()
|
||||
|
||||
for i = 0,25 do
|
||||
local c = a + i
|
||||
local C = A + i
|
||||
local rc = a + (i+k) % 26
|
||||
local RC = A + (i+k) % 26
|
||||
t[c], t[C] = rc, RC
|
||||
end
|
||||
|
||||
return t
|
||||
end
|
||||
|
||||
local function caesar(str, k, decode)
|
||||
k = (decode and -k or k) % 26
|
||||
|
||||
local t = memo[k]
|
||||
if not t then
|
||||
t = make_table(k)
|
||||
memo[k] = t
|
||||
end
|
||||
|
||||
local res_t = { str:byte(1,-1) }
|
||||
for i,c in ipairs(res_t) do
|
||||
res_t[i] = t[c] or c
|
||||
end
|
||||
return string.char(unpack(res_t))
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue