#479 · Codes and ciphers · Expert · 250 XP · about 55 min
The Enigma machine encrypted messages with rotors: wired wheels that scramble the alphabet and turn after every key press, so the same letter comes out differently each time. Write enigma(text, rotors, start, plugs) that returns text encrypted by the simplified Enigma described here.
The parts. Letters are numbered A = 0, B = 1, up to Z = 25. Each rotor has a wiring, a string of 26 letters, and a notch letter; the reflector is one more wiring. Your starter code has them all, as the dictionary ROTORS (name: (wiring, notch)) and the string REFLECTOR:
Rotor Wiring Notch I EKMFLGDQVZNTOWYHXUSPAIBRCJ Q II AJDKSIRUXBLHWTMCQGZNPYFVOE E III BDFHJLCPRTXVZNYEIWGAKMUSQO V IV ESOVPZJAYQUIRHXLNFTGKDCMWB J V VZBRGITYUPSDNHLXAWMJQOFEKC Z Reflector YRUHQSLDPXNGOKMIEBFZCWVJAT
rotors names three different rotors from left to right, for example ['I', 'II', 'III'].start is three capital letters: the starting positions of the left, middle and right rotor (a position is a letter, A = 0 to Z = 25).plugs is a list of two-letter strings such as 'AQ': the plugboard swaps the two letters of each pair. No letter is in more than one pair, and the list may be empty.Stepping. Before each letter is encrypted, the rotors turn, depending on where they were before this key press:
Moving one place means the position goes up by 1, wrapping from Z back to A. Because of the first rule, the middle rotor moves on two key presses in a row when it reaches its own notch, exactly as the real machine did.
The path of a letter. After the stepping, the letter's number c travels:
(w[(c + p) % 26] - p) % 26, where w[i] means the number of the i-th letter of the wiring;REFLECTOR[c];(j - p) % 26, where j is the place in its wiring that holds the letter numbered (c + p) % 26;Letters of text, upper or lower case, are encrypted and written in upper case. Every other character is copied unchanged and does not turn the rotors.
enigma("AAAAA", ["I", "II", "III"], "AAA", []) # returns 'BDZGO' enigma("BDZGO", ["I", "II", "III"], "AAA", []) # returns 'AAAAA' enigma("Hi there!", ["III", "I", "V"], "KEY", ["AB", "QZ"]) # returns 'QP WZPQF!'
In the first example the right rotor moves from A to B before the first letter, and the first A comes out as B. The second example shows the machine's best-known property: with the same settings, encrypting the encrypted text gives the message back.
text has 0 to 30,000 characters.plugs has 0 to 13 pairs.First solves only, ranked by stars and then time.