Skip to content

Commit 33a8ca8

Browse files
committed
Added Caesar-Cipher problem solution
1 parent f847968 commit 33a8ca8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Caesar Cipher/main.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env node
2+
3+
// Problem Description at -> https://www.hackerrank.com/challenges/caesar-cipher-1/problem
4+
5+
6+
// O(N) Solution
7+
function caesarCipher(s, k) {
8+
let encryptedOutput = '';
9+
10+
for (let i = 0; i < s.length; i++) {
11+
let encryptedCharCode = s[i].charCodeAt(0) + k;
12+
13+
if (encryptedCharCode > 122)
14+
// Alternative traditional O(n^2) solution approach
15+
// while (encryptedCharCode > 122) encryptedCharCode -= 26;
16+
encryptedCharCode = ((encryptedCharCode - 97) % 26) + 97;
17+
18+
if (encryptedCharCode > 90 && /[A-Z]/.test(s[i]))
19+
// while (encryptedCharCode > 90) encryptedCharCode -= 26;
20+
encryptedCharCode = ((encryptedCharCode - 65) % 26) + 65;
21+
22+
const encryptedChar = String.fromCharCode(encryptedCharCode);
23+
// A regex to exclude the numbers and symbols from the output character set
24+
encryptedOutput += /[-!$%^&*()_+|~=`{}\[\]:";'<>?,\\.\/]|[0-9]/.test(s[i]) ? s[i] : encryptedChar;
25+
}
26+
27+
return encryptedOutput;
28+
}
29+
30+
// Test cases
31+
// console.log(caesarCipher('middle-Outz', 2)); // okffng-Qwvb
32+
// console.log(caesarCipher('There\'s-a-starman-waiting-in-the-sky', 3)); // Wkhuh'v-d-vwdupdq-zdlwlqj-lq-wkh-vnb
33+
// console.log(caesarCipher('This-is-a-string', 7)); // Aopz-pz-h-zaypun
34+
// console.log(caesarCipher('This-is-a-string', 0)); // This-is-a-string
35+
console.log(
36+
caesarCipher(
37+
'DNFjxo?b5h*5<LWbgs6?V5{3M].1hG)pv1VWq4(!][DZ3G)riSJ.CmUj9]7Gzl?VyeJ2dIPEW4GYW*scT8(vhu9wCr]q!7eyaoy.', 100));
38+
// WGYcqh?u5a*5<EPuzl6?O5{3F].1aZ)io1OPj4(!][WS3Z)kbLC.VfNc9]7Zse?OrxC2wBIXP4ZRP*lvM8(oan9pVk]j!7xrthr.
39+
// console.log(caesarCipher('w', 100)); // v
40+
// console.log(caesarCipher('x', 55)); // a
41+
// console.log(caesarCipher('a', 45)); // t

0 commit comments

Comments
 (0)