-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathcaesar.jl
66 lines (53 loc) · 1.25 KB
/
caesar.jl
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
caesar(rot, s)
Program to implement rotational cipher for the given sentence. A full description of the algorithm can be found on [wikipedia](https://en.wikipedia.org/wiki/Caesar_cipher)
# Arguments:
- `rot`: The number of rotations needed.
- `s` : The sentence needed to rotate
# Examples/Tests
```julia
julia> caesar(13,"abcdefghijklmnopqrstuvwxyz")
nopqrstuvwxyzabcdefghijklm
julia> caesar(5,"omg")
trl
julia> caesar(0,"hello")
hello
```
# Algorithm:
```julia
if r >= 'a' && r <= 'z'
v = ((r - 'a') + rot) % 26
return v + 'a'
end
if r >= 'A' && r <= 'Z'
v = ((r - 'A') + rot) % 26
return v + 'A'
end
return r
```
# References:
https://en.wikipedia.org/wiki/Caesar_cipher
```
# Contributed by:- [Ihjass Thasbekha](https://github.com/Ihjass)
"""
function caesar(rot, s)
rotate = function (r)
if 'a' <= r <= 'z'
v = ((r - 'a') + rot) % 26
return v + 'a'
end
if 'A' <= r <= 'Z'
v = ((r - 'A') + rot) % 26
return v + 'A'
end
return r
end
if s isa Char
return rotate(s)
end
result = ""
for r in s
result *= rotate(r)
end
return result
end