Editor

Columnar Transposition Cipher

#329 · Codes and ciphers · Intermediate · 80 XP · about 16 min

This cipher keeps every character of a message but mixes up their order. To encrypt with a keyword of length k:

  • write the message row by row into a grid with k columns, one character per cell (every character counts, spaces and punctuation included); the last row may be shorter than the others, and nothing is added to fill it;
  • write the keyword's letters above the columns, one letter per column;
  • read the columns out, each from top to bottom, one column after another, in the alphabetical order of their keyword letters; when a letter appears more than once in the keyword, its columns are read from left to right.

Write columnar(text, key, decrypt=False) that returns the encrypted text, or, when decrypt is True, turns encrypted text back into the original message. key is made of capital letters.

Examples

columnar("HELLOWORLD", "BAD")                # returns 'EORHLODLWL'
columnar("EORHLODLWL", "BAD", decrypt=True)  # returns 'HELLOWORLD'
columnar("ATTACKATDAWN", "BOOK")             # returns 'ACDATNTKATAW'

For the first example the grid is:

B A D
-----
H E L
L O W
O R L
D

In alphabetical order the columns are A (EOR), B (HLOD) and D (LWL). In the last example the keyword has two O columns, so the left one is read before the right one.

Constraints

  • text has 0 to 20,000 characters.
  • key has 1 to 26 capital letters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.