So Hopper’s Amazing Decipherer Script 1.0 was about 472 lines because it included ELSE IF clauses for every letter in the alphabet.
HADS 2.0 cuts it down to 77 lines because arrays, as it turns out, are incredibly useful when paired with loops.
Making a Rotated Alphabet
Deciphering a Caesar cipher requires that the alphabet be moved up by a certain number. Like so.
Notice that this is basically a 2-step process. Turn the letters of the alphabet into numbers 1-26. Then add the rotational value to each of them to find their new positions, in the code below that’s assigned to a variable called indexVar. In ROT1, A =1 and the rotational value is 1, so A = 1+1 = 2.
But what happens when you hit Z? Z=26 and the rotation is 1, so Z = 26+1 = 27.
So, you want to tell the computer IF the number goes above 27, then you want to reset it to 1 and continue.
A Slow Motion Loop
Remember A_Index is variable you can use with any loop. It is equal to the current loop cycle. Here’s what it looks like rotating the alphabet by 7.
That loop will get you the rotated alphabet, but you’ll need 5 total. 1 is the abcArray for reference with letters a-z at indexes 1-26. 2 is the rotArray above. 3 contains every letter of the enciphered message. 4 is the enciphered message array converted into numbers 1-26. And finally, 5 is the product of cross referencing the enciphered message with the rotated alphabet to get the deciphered message.
If you find this confusing, join the club. I’m baffled. But it works.
Here’s a really thorough breakdown for the masochists: