#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:
Encrypting a pair. Find both letters in the square:
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.
text has 0 to 50,000 characters.key has 0 to 100 characters.First solves only, ranked by stars and then time.