In English, E is the most common letter. A Caesar cipher keeps letter counts, so its most common letter probably stands for E.
What to build
Find the shift of a Caesar-encrypted message by frequency analysis, and print the message decrypted.
Requirements
- Count the letters A to Z over all the lines together, ignoring case.
- Take the most common letter as the one that stands for E. If several letters tie, take the one that comes first in the alphabet.
- The shift is the distance from E to that letter, from 0 to 25.
- Print
shift N, then every line decrypted with that shift, keeping case and other characters.
Input
One or more lines of cipher text.
Output
The shift line, then the decrypted lines.
Constraints
1 to 20 lines, with at least one letter in total.
Example
Input:
Wkh hadp ehjlqv dw whq, vr phhw ph dw wkh vwdwlrq dw qlqh
Output:
shift 3
The exam begins at ten, so meet me at the station at nine
Why it works
A substitution keeps how often each letter appears, so the cipher's most common letter is usually E moved by the shift, and the distance between them recovers the key.
Examples
Wkh hadp ehjlqv dw whq, vr phhw ph dw wkh vwdwlrq dw qlqh
shift 3 The exam begins at ten, so meet me at the station at nine
Ymj xhmjizqj nx kwjj ymnx bjjp
shift 5 The schedule is free this week
Hints
Hint 1
Read all the lines into an array first; you need the counts before you can decrypt any line.
Hint 2
shift = (most - 4 + 26) % 26, where most is the most common letter's position (A = 0) and 4 is E's.
Solution
Show one correct solution (try it yourself first)
const lines = [];
let line = prompt();
while (line !== null) {
lines.push(line);
line = prompt();
}
const counts = new Array(26).fill(0);
for (const l of lines) for (const ch of l.toUpperCase()) if (ch >= "A" && ch <= "Z") counts[ch.charCodeAt(0) - 65]++;
let most = 0;
for (let k = 1; k < 26; k++) if (counts[k] > counts[most]) most = k;
const shift = (most - 4 + 26) % 26;
console.log(`shift ${shift}`);
const back = (ch, base) => String.fromCharCode(((ch.charCodeAt(0) - base - shift + 26) % 26) + base);
for (const l of lines) {
let out = "";
for (const ch of l) out += ch >= "A" && ch <= "Z" ? back(ch, 65) : ch >= "a" && ch <= "z" ? back(ch, 97) : ch;
console.log(out);
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step