Skip to main content
4 of 4
added 383 characters in body
Massimo
  • 145
  • 7

Substitution cipher

A substitution cipher is an encoding method where each letter in the alphabet is replaced with a fixed, different one; for example, given the following substitution map:

abcdefghijklmnopqrstuvwxyz
            ||
qwertyuiopasdfghjklzxcvbnm

The phrase "we all love cryptography" would be encoded as "vt qss sgct eknhzgukqhin".

The program will continuously read its input, one line at time; the first line will contain the substitution map, in the form of all 26 letters, in any order, without repetitions, missing letters or extraneous characters; it will be interpreted as "the first letter is the substitution for A, the second letter is the substitution for B [...] the 26th letter is the substitution for Z"; no output will be provided after reading it. For each subsequent line, the program will output the encoded text corresponding to the line. Only letters will be encoded; numbers, symbols and whitespaces will be simply copied to the output.

For simplicity, all input (including the substitution map) will only contain lowercase characters.

Sample input:

qwertyuiopasdfghjklzxcvbnm
hello
bye!
i don't know.

Sample output:

itssg
wnt!
o rgf'z afgv.
    

As usual, the shortest solution wins.


Additional clarifications on input:

  • The program must read its input stream (I thought that was clear); command line parameters, files, named pipes, network sockets, quantum entanglement or extra sensorial perceptions are not allowed.
  • The input must include only the actual text to be processed; quotes, brackets, commas or any other symbol, if found, should simply be copied to the output as they are.
  • No additional characters should be required in the input. If your program requires the input text to be placed in quotes, brackets, commas or any other delimiter, then You Are Doing It Wrong (TM).
  • "Line" is defined as a string of characters followed by a newline; the actual implementation of "newline" if usually left to the OS, but if you need to go into its details, just use whatever you prefer.
  • An empty line is no special case; the program could either print an empty line or do nothing, but it should not print any actual text, crash, exit, destroy the operating system, set fire to the house, collapse the Sun in a black hole, summon demons from other planes of existence or replace your toothpaste with mayonnaise.
  • There is no requirement for the program to run interactively; it's free to suck all its input in and then print all its output; there is also not any time limit on its execution, although it would be definitely preferable for it to terminate before the heat death of the universe.
Massimo
  • 145
  • 7