Why Is My Caesar Cipher Code Skipping Over Some Characters? - javascript

I have the code below for a Caesar Cipher to increment by 13 characters on each input character. It works for almost all inputs, but will seemingly skip over random chacaters. I just can't seem to figure out why?! I'm still learning, so any help would be fantastic!
The input is a coded string of characters that will be output with each character shifted forward 13 places. The expected output should be a readable string.
If I input rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.') I would expect 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.' But instead I get 'T H E Q U I C K B R O W N F B X J H M P S B V R E G U R L A Z Y D B G .'
I appreciate this could be a duplicate, but I couldn't find an answer to this particular problem so far.
function rot13(str) {
let newStr = [];
for (let i = 0; i < str.length; i++) {
let charNum = str.charCodeAt(i);
console.log(charNum);
if (charNum > 64 && charNum < 78) {
let res = str.replace(str[i], String.fromCharCode(charNum + 13));
newStr.push(res[i]);
} else if (charNum > 77 && charNum < 91) {
let res = str.replace(str[i], String.fromCharCode(charNum - 13));
newStr.push(res[i]);
} else {
newStr.push(str[i]);
}
}
console.log(newStr);
return newStr.join(" ");
}
rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.');

String.fromCharCode(charNum + 13) & String.fromCharCode(charNum - 13) are all you need. You don't need to replace the char at index i in str.
newStr.push(String.fromCharCode(charNum + 13));
newStr.push(String.fromCharCode(charNum - 13));

Problem is in your second condition:
let res = str.replace(str[i], String.fromCharCode(charNum - 13));
But even without that your code is over engineered. A bit modified version
function rot13(str) {
let newStr = [];
for (let i = 0; i < str.length; i++) {
let charNum = str.charCodeAt(i);
//console.log(charNum);
if (charNum > 64 && charNum < 78) {
let res = String.fromCharCode(charNum + 13);
newStr.push(res);
} else if (charNum > 77 && charNum < 91) {
let t = charNum + 13 - "Z".charCodeAt(0);
let res = String.fromCharCode("A".charCodeAt(0) - 1 + t);
newStr.push(res);
} else {
newStr.push(str[i]);
}
}
return newStr.join(" ");
}
There are even better solutions, but for beginner this should do it.

Related

Need help solving a javascript Caesar Cipher problem

I'm stuck doing the Caesar cipher problem. For those of you familiar with the problem, I'm not able to wrap around the alphabet, for example if I want to shift the string 'z' by 1, instead of getting 'a', i'll get '['. I know the reason this happens but I'm not able to come up with the proper code. Any help will be appreciated.
Here's my code:
const caesar = function(word, num) {
let solved = ""
num = num % 26;
for (let i = 0; i < word.length ; i++) {
let ascii = word[i].charCodeAt();
if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
solved += String.fromCharCode(ascii + num) ;
} else {
solved += word[i]
}
}
return solved;
}
You need to take the modulus under 26 after subtracting the char code of the first letter of the alphabet and add it back afterward to allow the cipher to wrap around. You will need to handle capital and lowercase letters separately.
const caesar = function(word, num) {
let solved = ""
num = (num%26 + 26) % 26;
for (let i = 0; i < word.length ; i++) {
let ascii = word[i].charCodeAt();
if ((ascii >= 65 && ascii <= 90)) {
solved += String.fromCharCode((ascii - 'A'.charCodeAt(0) + num)%26
+ 'A'.charCodeAt(0)) ;
} else if(ascii >= 97 && ascii <= 122){
solved += String.fromCharCode((ascii-'a'.charCodeAt(0) + num) % 26
+ 'a'.charCodeAt(0));
} else {
solved += word[i]
}
}
return solved;
}
console.log(caesar("abcdefghijklmnopqrstuvwxyzABCDEFGHI", 7));
Do the modulus when you add num to your ascii value. This way you don't scroll past the end of the range (and loop around if you are through the modulus (remainder)).
solved += String.fromCharCode((ascii + num)%26) ;
Out of interest, the ASCII codes for 'A` and 'a' are 0x41 and 0x61 respectively: upper and lower case letters differ by whether bit 0x20 is set (lower case) or not set (upper case).
Hence a bit-bashing algorithm to circular shift ASCII letters and maintain case would be strip the lower case bit, perform the shift, and re-insert the case bit:
"use strict";
function caesarShiftLetter( letter, num) {
let code = letter.charCodeAt(0);
let lowerCaseBit = code & 0x20; // 0 or 0x20
let upperCaseCode = code - lowerCaseBit;
if( upperCaseCode < 0x41 || upperCaseCode >= 0x41 + 26) {
return letter;
}
num = 26 + num%26; // handle large negative shift values
upperCaseCode = ((upperCaseCode - 0x41) + num) % 26 + 0x41;
return String.fromCharCode( upperCaseCode | lowerCaseBit);
}
// to test:
function caesarShiftString( str, num) {
return Array.from(str).map(char => caesarShiftLetter( char, num)).join('');
}
console.log( caesarShiftString(
"abc ... xyz, ABC ... XYZ, I, II, III, IV, V, VI, VII, VIII, IX, X - 1,3,4,5,6,7,9, 10",-22
)
);

My decipher call is returning an invalid response when trying to implement Ceasar cipher, why?

functionmovingShift() performs a variation of the Caesar shift. The shift increases by 1 for each character (including spaces character).
Function demovingShift() should decipher returned string backwards.
I can't figure out the algorithm to decipher the returned string.
My code works only for the first few words. Then as "shift" variable grows negative the logic breaks.
let u = "I should have known that you would have a perfect answer for me!!!";
function movingShift(s, shift) {
let arr = [];
s.split("").forEach((x, idx) => {
let source = x.toUpperCase().charCodeAt(0);
if (source < 65 || source > 90) {
arr.push(x);
shift++;
return;
}
let index = (source - 65 + (shift)) % 26 + 65;
let letter = String.fromCharCode(index);
x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
shift++;
})
let cipher = arr.join("");
return cipher;
}
let v = movingShift(u, 1);
function demovingShift(v, shift) {
shift = -1;
let arr = [];
v.split("").forEach((x, idx) => {
let source = x.toUpperCase().charCodeAt(0);
if (source < 65 || source > 90) {
arr.push(x);
shift--;
return;
}
let index = (source - 65 + (shift)) % 26 + 65;
let letter = String.fromCharCode(index);
x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
shift--;
})
return arr.join("");
}
console.log(movingShift(u, 1));
console.log(demovingShift(v, 1));
Returned string from the first function :
J vltasl rlhr zdfog odxr ypw atasl rlhr p gwkzzyq zntyhv lvz wp!!!
Returned string from decipher function:
I sho;ld ha<e k45=4 :.a: ?5; =5;2* .a<+ a 6+8,+): a49=+8 ,58 3+!!!
There are two mistakes in your code.
1) First inside demovingShift you need to change shift = -1 to shift = -1 * shift;.
2) Change let index = (source - 65 + (shift)) % 26 + 65; to let index = (source - 65 + (shift)) % 26 + 65; because now shift is negative its possible that (source - 65 + (shift)) value may became negative which will give incorrect character. So we can use (source + 65 + (shift)).
You can test it below.
let u = "I should have known that you would have a perfect answer for me!!!";
function movingShift(s, shift) {
let arr = [];
s.split("").forEach((x, idx) => {
let source = x.toUpperCase().charCodeAt(0);
if (source < 65 || source > 90) {
arr.push(x);
shift++;
return;
}
let index = (source - 65 + (shift)) % 26 + 65;
let letter = String.fromCharCode(index);
x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
shift++;
})
let cipher = arr.join("");
return cipher;
}
function demovingShift(v, shift) {
shift = -1 * shift;
let arr = [];
v.split("").forEach((x, idx) => {
let source = x.toUpperCase().charCodeAt(0);
if (source < 65 || source > 90) {
arr.push(x);
shift--;
return;
}
let index = (source + 65 + (shift)) % 26 + 65;
let letter = String.fromCharCode(index);
x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
shift--;
})
return arr.join("");
}
let v = movingShift(u, 1);
console.log(u);
console.log(v);
console.log(demovingShift(v, 1));

Caesars Cipher in JavaScript - Why does 'A' turn into '[' here?

I'm currently going through a FreeCodeCamp challenge that requests you to create a ROT13 cipher (a very simple cipher that shifts each letter to be the letter 13 letters ahead of it in a never-ending alphabet). My code is below:
function rot13(str) {
let lettersRegex = /[A-Z]/;
let alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
let charCodes = [];
for(let i = 0; i < str.length; i++) {
if(str.charAt(i).match(lettersRegex)) {
charCodes.push(str.charCodeAt(i));
} else {
charCodes.push(str.charAt(i));
}
}
let ret = '';
console.log(`charCodes is currently ${charCodes}`);
for(let i = 0; i < charCodes.length; i ++) {
let temp = 0;
if(lettersRegex.test(String.fromCharCode(charCodes[i]))) {
if((alphabet.indexOf(String.fromCharCode(charCodes[i])) + 13) > alphabet.length) {
temp = charCodes[i] + alphabet.indexOf(charCodes[i]) - 12;
}
else {
temp = charCodes[i] + 13;
}
ret += String.fromCharCode(temp);
} else {
ret += charCodes[i];
}
}
console.log(ret);
return ret;
}
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.");
//THE QUICK BROWN FOX JUMPS OVER THE L[ZY DOG.
Basically, every letter but 'A' shifts to the correct answer after the cipher. What could be causing 'A' to turn into '[' instead of 'N' in this code?
Any comments or tips on my code would also be much appreciated.
It's a simple fix, changing > to >= Don't forget that arrays are zero-indexed.
if((alphabet.indexOf(String.fromCharCode(charCodes[i])) + 13) >= alphabet.length)

Caesar Cipher in Javascript

I am trying to write a program to solve the following problem in javascript (Written below this paragraph). I don't know why my code isn't working. Could someone help me? I'm new to javascript; this is a free code camp question.
"A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.
Write a function which takes a ROT13 encoded string as input and returns a decoded string."
function rot13(str) { // LBH QVQ VG!
var string = "";
for(var i = 0; i < str.length; i++) {
var temp = str.charAt(i);
if(temp !== " " || temp!== "!" || temp!== "?") {
string += String.fromCharCode(13 + String.prototype.charCodeAt(temp));
} else {
string += temp;
}
}
return string;
}
// Change the inputs below to test
console.log(rot13("SERR PBQR PNZC")); //should decode to "FREE CODE CAMP"
Using modulus operator; makes the sentence uppercase;
function cipherRot13(str) {
str = str.toUpperCase();
return str.replace(/[A-Z]/g, rot13);
function rot13(correspondance) {
const charCode = correspondance.charCodeAt();
//A = 65, Z = 90
return String.fromCharCode(
((charCode + 13) <= 90) ? charCode + 13
: (charCode + 13) % 90 + 64
);
}
}
I have tried to make it simple and I earned FREE PIZZA!. Check my solution for this.
function rot13(str) {
var alphabets =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'," ", "-", "_", ".", "&","?", "!", "#", "#", "/"];
var alphabets13 = ['N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','B','C','D','E','F','G','H','I','J','K','L','M', " ", "-", "_", ".", "&","?", "!", "#", "#", "/"];
var resultStr = [];
for(let i=0; i<str.length; i++){
for(let j =0; j<alphabets.length; j++){
if(str[i] === alphabets[j]){
resultStr.push(alphabets13[j]);
}
}
}
return resultStr.join("");
};
rot13("SERR CVMMN!");
You can build the algorithm for ROT13 directly... or just use a Caesar Cipher algorithm with the appropriate key.
The alternative that I'm proposing to your example is just a particular usage of a regular Caesar Cipher algorithm – a very simple form of encryption, in which each letter in the original message is shifted to the left or right by a certain number of positions.
To decrypt the message we simply shift back the letters the same number of positions.
Example:
JAVASCRIPT becomes MDYDVFULSW if we shift all letters by 3 positions
MDYDVFULSW turns back to JAVASCRIPT if we shift back all letters by 3 positions.
If after shifting a letter goes outside the range of letters, then the letter is wrapped around in alphabet. Example: Letter Z becomes C if is shifted by 3 positions.
This “wrap-around” effect means use of modulo. In mathematical terms, the above can be expressed as this:
En(x) = (x + n) mod 26
Dn(x) = (x – n) mod 26
Trying to implement this algorithm in JavaScript without the use of a proper modulo operator will produce either incorrect results or a very cryptic and difficult to understand code.
The biggest problem is that JavaScript doesn't contain a modulo operator. The % operator is just the reminder of the division - not modulo. However, it is pretty easy to implement modulo as a custom function:
// Implement modulo by replacing the negative operand
// with an equivalent positive operand that has the same wrap-around effect
function mod(n, p)
{
if ( n < 0 )
n = p - Math.abs(n) % p;
return n % p;
}
There are other ways of implementing modulo... if you are interested you can consult this article.
By using the mod function defined above, the code expresses the mathematical equation identically:
// Function will implement Caesar Cipher to
// encrypt / decrypt the msg by shifting the letters
// of the message acording to the key
function encrypt(msg, key)
{
var encMsg = "";
for(var i = 0; i < msg.length; i++)
{
var code = msg.charCodeAt(i);
// Encrypt only letters in 'A' ... 'Z' interval
if (code >= 65 && code <= 65 + 26 - 1)
{
code -= 65;
code = mod(code + key, 26);
code += 65;
}
encMsg += String.fromCharCode(code);
}
return encMsg;
}
To encode using ROT13 ... is now just a matter of choosing the appropriate key as indicated by algorithm name.
2020 TypeScript Version:
A shift argument must be given, but you can choose 13 for rot13 or any other number.
// TypeScript Type: Alphabet
type Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Helper Function: Caesar Cipher
export const caesarCipher = (string: string, shift: number) => {
// Alphabet
const alphabet: Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Encoded Text
let encodedText: string = '';
// Adjust Shift (Over 26 Characters)
if (shift > 26) {
// Assign Remainder As Shift
shift = shift % 26;
}
// Iterate Over Data
let i: number = 0;
while (i < string.length) {
// Valid Alphabet Characters
if (alphabet.indexOf(string[i]) !== -1) {
// Find Alphabet Index
const alphabetIndex: number = alphabet.indexOf((string[i]).toUpperCase());
// Alphabet Index Is In Alphabet Range
if (alphabet[alphabetIndex + shift]) {
// Append To String
encodedText += alphabet[alphabetIndex + shift];
}
// Alphabet Index Out Of Range (Adjust Alphabet By 26 Characters)
else {
// Append To String
encodedText += alphabet[alphabetIndex + shift - 26];
}
}
// Special Characters
else {
// Append To String
encodedText += string[i];
}
// Increase I
i++;
}
return encodedText;
};
Example #1:
console.log(caesarCipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 2));
Output:
CDEFGHIJKLMNOPQRSTUVWXYZAB
Example #2:
console.log(caesarCipher('GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.', 26 + 13));
Output:
THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX.
I just recently solved a caesar cipher algorithm problem that works similarly to your rot13, but will take any integer value as a shift parameter. One of the issues I notice with your code is you are already assigning temp as a number by assigning the charCode for the character at 'i'. This makes your conditional obsolete, since it will never identify the string values, since you're passing in a number value. Also, when you build the string, it should just be 'String.fromCharCode(13 + temp)'. I personally prefer the caesar cipher, since you can assign random shift parameters.
Here's an example of how I wrote it:
// s = string to encrypt, k = shift value
// s = 'SERR PBQR PNZC' and k = 13 will produce 'FREE CODE CAMP'
const caesarCipher = function(s, k) {
let result = '';
for (let i = 0; i < s.length; i++) {
let charCode = s[i].charCodeAt();
// check that charCode is a lowercase letter; automatically ignores non-letters
if (charCode > 96 && charCode < 123) {
charCode += k % 26 // makes it work with numbers greater than 26 to maintain correct shift
// if shift passes 'z', resets to 'a' to maintain looping shift
if (charCode > 122) {
charCode = (charCode - 122) + 96;
// same as previous, but checking shift doesn't pass 'a' when shifting negative numbers
} else if (charCode < 97) {
charCode = (charCode - 97) + 123;
}
}
if (charCode > 64 && charCode < 91) {
charCode += k % 26
if (charCode > 90) {
charCode = (charCode - 90) + 64;
} else if (charCode < 65) {
charCode = (charCode - 65) + 91;
}
}
result += String.fromCharCode(charCode);
}
return result
}
Note : This function will take care of alphabetic(a-z or A-Z) and all others will be ignored.
Considered points are
Handle negative number
Can take care of big number.
Handle special character, number and space will print as it is
sd
function caesarCipher(word, next) {
next = next % 26;
let res = "";
for (const letter of word) {
let letterCode = letter.charCodeAt(0);
if (letterCode >= 65 && letterCode <= 90) {
letterCode = letterCode + next;
if (letterCode > 90) {
letterCode = letterCode - 26;
} else if (letterCode < 65) {
letterCode = letterCode + 26;
}
} else if (letterCode >= 97 && letterCode <= 122) {
letterCode = letterCode + next;
if (letterCode > 122) {
letterCode = letterCode - 26;
} else if (letterCode < 97) {
letterCode = letterCode + 26;
}
}
res = res + String.fromCharCode(letterCode);
}
return res; }
console.log(caesarCipher("Zoo Keeper 666 %^&*(", 2));
console.log(caesarCipher("Big Car", -16));
Output
Bqq Mggrgt 666 %^&*(
Lsq Mkb
Here's a simple solution.
function caesar(str) {
str = str.split("")
str = str.map(char => {
let code = char.charCodeAt(0)
if( (code > 64 && code < 78) || (code > 96 && code < 110) )
code += 13
else if ( (code > 77 && code < 91) || (code > 109 && code < 123) )
code -= 13
return String.fromCharCode(code)
})
return str.join("")
}
const rot13 = (string) => {
// creating *letterBox* - string in alphabetic way
const letterBox = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// declaring *iter function* - that will pass through the text
const iter = (str, acc) => {
// if length of string is 0 (phrase is empty) => returning *accumulator*
if (str.length===0) { return acc; }
/* if is not an uppercase character => calling *function iter* by itself
with the new string minus first letter and adding to *accumulator*
without coding symbol */
if (! /^[A-Z]*$/.test(str[0])) {return iter(str.substring(1), acc+str[0]); };
// and now we loop through the uppercase letters (26 letters)
//checking their index in our *letterBox*
// if it's more that 13 , we add 13 , else we substract 13 and
// and of course... calling *iter function* with new string minus first character
// plus *accumumator*
for (let i=0; i<26;i++)
{
if ( (letterBox[i]===str[0]) && (i>12))
{ return iter(str.substring(1), acc + letterBox[i-13]); }
if ( (letterBox[i]===str[0])&& (i<13))
{ return iter(str.substring(1), acc + letterBox[i+13]); };
};
};
// calling *iter function* with the provided *string* and empty *accumulator*
return iter(string,'');
};
console.log(rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.'));
// THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
passed with success test on codecamp.
also there is another version.. without iter function
const rot13=(str) =>
{
var alph= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result ='';
while(str.length>0)
{
for (let i=0;i<=25;i++)
{
if ((alph[i]===str[0]) && (i>13)) {result = result + alph[i-13];};
if ((alph[i]===str[0]) && (i<13)) {result = result + alph[i+13] ;} ;
};
if (! /^[A-Z]*$/.test(str[0]) ) {result = result+ str[0];};
str=str.substring(1);
};
return result;
};
console.log(rot13('SERR YBIR?'));
// returns FREE LOVE?
I am recently in my first stage of developing a javascript library to simplify my daily programming requirements.
One of which is Encryption.
The library uses caesar encryption as of now.
You may download the minified version in the early development and use it in your html pages as:
d(window).loaded(function() {
/* *
* Tidy up the heading
* */
d("h1")
.background("#fafafa")
.color("orange");
/* *
* Encrypt all paragraphs and maximize the height so we view each paragraph separately
* */
d("p")
.encrypt(text = "", depth = 15)
.resize("60%", "50px");
/* *
* Show up the first paragraph element's html
* */
_.popUp("First Paragraph: <hr>" + dom("p").getText(), "", "purple")
})
/* *
* Show the inputed text in below snippet
* */
function showEncryptedText(){
d("#encrypted")
.encrypt(d("#plain").c[0].value, 15)
.background("#e8e8e8")
.resize("100%", "100px");
}
<!DOCTYPE HTML>
<html>
<head>
<title>Element Encryption</title>
<script type="text/javascript" src="https://raw.githubusercontent.com/Amin-Matola/domjs/master/dom-v1.0.0/dom.min.js"></script>
</head>
<body>
<h1>Javascript Encryption</h1>
<p>This is the first paragraph you may encrypt</p>
<p>This is another paragraph you may encrypt</p>
<p>You may encrypt this too</p>
<h2>You may even provide your text to be encrypted</h2>
<div id="encrypted">
</div>
<input type="text" id="plain" value="" name="mydata" oninput="showEncryptedText()"/>
</div>
<footer>
<!--- you may place your js here --->
<script type="text/javascript">
</script>
</body>
</html>
I just solved the caesar chipper problem using this algorithm.
function rot13(str) {
const rot13 = {
'N': "A",
'O': 'B',
'P': 'C',
'Q': 'D',
'R': 'E',
'S': 'F',
'T': 'G',
'U': 'H',
'V': 'I',
'W': 'J',
'X': 'K',
'Y': 'L',
'Z': 'M',
'A': 'N',
'B': 'O',
'C': 'P',
'D': 'Q',
'E': 'R',
'F': 'S',
'G': 'T',
'H': 'U',
'I': 'V',
'J': 'W',
'K': 'X',
'L': 'Y',
'M': 'Z'
}
const splitStr = str.split(' ').map(string => {
return string.split('').map(string => rot13[string] === undefined ? string : rot13[string]).join('');
}).join(' ');
return splitStr;
}
I see that people here have written lengthy codes. I have solved the problem using a simple solution.
function replacing(str){
let strAm = "ABCDEFGHIJKLMNOPQRSTUVWXYZ -_.&?!# #/";
let strNz = "NOPQRSTUVWXYZABCDEFGHIJKLM -_.&?!# #/";
let rot13 = '';
for (let i = 0; i < str.length; i++){
if (strAm.includes(str.charAt(i))){
rot13 += str.charAt(i).replace(str.charAt(i), strNz[strAm.indexOf(str.charAt(i))]);
}
}
return rot13;
}
console.log(replacing("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT."));
This problem can be solved in many ways.
Below is the code using ASCII code of the characters in ths string and with two built in JavaScript functions i.e., charCodeAt() and String.fromCharCode()
function rot13(message) {
let cipherString = '';
let arr = [...message];
for (let i = 0; i < arr.length; i++) {
let asciiValue = arr[i].charCodeAt();
if (
(asciiValue >= 65 && asciiValue <= 90) ||
(asciiValue >= 97 && asciiValue <= 122)
) {
if (asciiValue >= 65 && asciiValue <= 90) {
if (asciiValue <= 77) {
asciiValue += 13;
} else {
asciiValue -= 13;
}
} else {
if (asciiValue <= 109) {
asciiValue += 13;
} else {
asciiValue -= 13;
}
}
cipherString += String.fromCharCode(asciiValue);
} else cipherString += arr[i];
}
return cipherString;
}
I wanted to post my way to do it in typestcript.
function caesarCipher(s: string, k: number): string {
//[ [ 'A', 65 ], [ 'Z', 90 ], [ 'a', 97 ], [ 'z', 122 ] ]
return [...s]
.map(l => (l.charCodeAt(0)))
.map(n => n >= 65 && n <= 90 ? ((n - 65 + k) % 26) + 65 : n)
.map(n => n >= 97 && n <= 122 ? ((n - 97 + k) % 26) + 97 : n)
.map(n => String.fromCharCode(n))
.join("")
}
Solution using for loop, in each iteration check if character is alphabet then decode it by subtracting 13 from it's ascii code, if decoded character is not alphabet (its ascii code is less than 65), then decode it by adding 13 to it.
function rot13(str) {
function isAlphabet(char) {
return String(char).match(/[A-Z]/);
}
const chars = str.split("");
for(let i = 0 ; i < chars.length; i++) {
const char = chars[i];
if(isAlphabet(char)) {
const decoded = String.fromCharCode(char.charCodeAt() - 13);
const decodedAlphabet = String.fromCharCode(char.charCodeAt() + 13);
chars[i] = isAlphabet(decoded)? decoded : decodedAlphabet;
}
}
return chars.join("")
}
Here is my approach - provide input and shift.
It maintains lower or upper case of original input and leave unprocessable letters in place:
ceasarCipher("Hello Stackoverflow!");
// Khoor Vwdfnryhuiorz!
function ceasarCipher(input: string, shift = 3) {
const letters = input.split("");
const anyLetter = /[a-z]/i;
return letters
.map((letter) => {
if (!anyLetter.test(letter)) return letter;
const upperLetter = letter.toUpperCase();
const wasOriginalUpper = letter === upperLetter;
const charCode = upperLetter.charCodeAt(0);
//A = 65, Z = 90
const maskedLetter = String.fromCharCode(
charCode + shift <= 90
? charCode + shift
: ((charCode + shift) % 90) + 64
);
if (wasOriginalUpper) {
return maskedLetter;
}
return maskedLetter.toLowerCase();
})
.join("");
}
Simple Implementation of Caesar's Cipher(From FREE CODE CAMP)
function rot13(str) {
const alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let ans="";
for(let i=0;i<str.length; i++){
const char=str[i];
if(char===" " || char==="!" || char==="?" || char==="."){
ans+=char;
}
else{
const val=alpha.indexOf(str[i]);
const new_val=(val+13)%26;
ans+=alpha[new_val];
}
}
return ans;
}
console.log(rot13("SERR PBQR PNZC"));
While A + 13 may equal N, Z + 13 will not compute correctly.

convert alphabets to coresponding numbers

i have to convert alphabets to corresponding numbers like i have a data like "DRSG004556722000TU77" and the index for A is 10, B is 11, C is 12 and so on up to Z is 35.
any helping tips??
here is the javascript which return me ascii code but i want to get the above indecies for respective alphabet
var string = DRSG004556722000TU77;
function getColumnName(string) {
return ((string.length - 1) * 26) + (string.charCodeAt(string.length - 1) - 64);
}
document.write( getColumnName(string) );
This may help
var output = [], code, str = 'DRSG004556722000TU77',i;
for(i in str){
code = str.charCodeAt(i);
if(code <= 90 && code >= 65){
// Add conditions " && code <= 122 && code >= 97" to catch lower case letters
output.push([i,code]);
}
}
Now ouput contains all letters codes and their corresponding indexes
var string = 'DRSG004556722000TU77';
function getColumnName(string) {
var recode = new Array(), i, n = string.length;
for(i = 0; i < n; i++) {
recode.push(filter(string.charCodeAt(i)));
}
return recode;
}
function filter(symbol) {
if ((symbol >= 65) && (symbol <= 90)) {
return symbol - 55;
} else if ((symbol >= 48) && (symbol <= 57)) {
return symbol - 48;
}
}
document.write(getColumnName(string));

Categories

Resources