Editor

Playfair Cipher

#391 · Codes and ciphers · Advanced · 140 XP · about 30 min

The Playfair cipher was used by soldiers in the field because it needs only a pencil and a 5 by 5 square of letters, yet it hides single-letter patterns by encrypting letters in pairs. Write playfair(text, key) that returns the encrypted text: capital letters only, with no spaces.

The square. Take the letters of key in upper case, ignoring everything that is not a letter and writing every J as I. Write them into the square row by row, left to right, skipping any letter that is already in it. Then fill the rest of the square with the remaining letters of the alphabet in order, leaving out J. The square holds every letter except J exactly once.

The pairs. Keep only the letters of text, in upper case, with every J changed to I. Split them into pairs from left to right:

  • if the two letters of a pair would be the same, put an X between them: the first letter and the X make a pair, and the second letter starts the next pair (when the doubled letter is X itself, use a Q instead of the X);
  • if one letter is left over at the end, add an X after it (or a Q if that letter is X).

Encrypting a pair. Find both letters in the square:

  • in the same row: replace each with the letter to its right, wrapping from the end of the row to its start;
  • in the same column: replace each with the letter below it, wrapping from the bottom to the top;
  • otherwise they are opposite corners of a rectangle: replace each with the letter in its own row but in the other letter's column.

Examples

playfair("Meet me at the bridge", "PYTHON CODE")  # returns 'RCDHRCDOHONIXRGQIH'
playfair("Balloon", "PYTHON CODE")                # returns 'KNRUSPPA'
playfair("Jazz", "")                              # returns 'FDVYVY'

The key "PYTHON CODE" gives this square:

P Y T H O
N C D E A
B F G I K
L M Q R S
U V W X Z

In the first example the pairs are ME ET ME AT TH EB RI DG EX: the E in the last pair has no partner, so an X joins it. ME is a rectangle: M becomes the letter in M's row and E's column, R, and E becomes the letter in E's row and M's column, C. In the second example the pairs are BA LX LO ON: an X splits the double L.

Constraints

  • text has 0 to 50,000 characters.
  • key has 0 to 100 characters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.