Shift each letter of a message along the alphabet.
What to build
The oldest code in history, which needs characters to be treated as numbers.
Requirements
- Read a whole number, the shift, and then a line of text.
- Move each letter forward through the alphabet by the shift, wrapping from
zround toa. - A negative shift moves backwards.
- Capital letters stay capital and small letters stay small. Anything else is unchanged.
Input
Two lines: the shift, then the text.
Output
One line: the changed text.
Constraints
The shift is from -1000 to 1000. The text has from 1 to 200 characters.
Example
Input:
3
Hello, World!
Output:
Khoor, Zruog!
Why it works
Subtracting the code of the first letter turns any letter into a position from 0 to 25, where the remainder operator can wrap it round. JavaScript's % keeps the sign of the left side, so adding 26 and taking the remainder again brings a negative result into range.
Examples
3 Hello, World!
Khoor, Zruog!
-1 Bcd
Abc
Hints
Hint 1
charCodeAt(0) gives a character's code, and String.fromCharCode turns a code back into a character.
Hint 2
Work out the letter's position from 0 to 25 by subtracting the code of "a" or "A".
Hint 3
In JavaScript, -1 % 26 is -1. Use ((x % 26) + 26) % 26 to get a position from 0 to 25.
Solution
Show one correct solution (try it yourself first)
const shift = Number(prompt());
const text = prompt();
function shifted(ch, first) {
const base = first.charCodeAt(0);
const position = ch.charCodeAt(0) - base;
return String.fromCharCode(base + (((position + shift) % 26) + 26) % 26);
}
let result = "";
for (const ch of text) {
if (ch >= "a" && ch <= "z") {
result += shifted(ch, "a");
} else if (ch >= "A" && ch <= "Z") {
result += shifted(ch, "A");
} else {
result += ch;
}
}
console.log(result);