aboutsummaryrefslogtreecommitdiff
path: root/challenge-097/paulo-custodio/lua/ch-1.lua
blob: 46c6b0f418e959dc324a71067c56e23e735cf5da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env lua

--[[
Challenge 097

TASK #1 › Caesar Cipher
Submitted by: Mohammad S Anwar
You are given string $S containing alphabets A..Z only and a number $N.

Write a script to encrypt the given string $S using Caesar Cipher with left
shift of size $N.

Example
Input: $S = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG", $N = 3
Output: "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD"

Plain:    ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher:   XYZABCDEFGHIJKLMNOPQRSTUVW

Plaintext:  THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
--]]

function caesar(n, text)
    local text = string.upper(text)
    local cipher = ""

    for i=1, #text do
        local c = string.sub(text,i,i)
        if c >= "A" and c <= "Z" then
            c = string.char((string.byte(c)-string.byte('A')+26-n)%26
                            +string.byte('A'))
        end
        cipher = cipher..c
    end
    return cipher
end

n = arg[1]
text = ""; for i=2,#arg do text = text..arg[i].." "; end
io.write(caesar(n, text),"\n")