Here are the letters of the English alphabet in order by frequency:
e t a o i n s h r d l c u m w f g y p b v k j x q z
That is, e
is the most frequently used letter, and z
is the least common. (Data from Wikipedia.)
Your challenge is to take some ROT-n'd text, such as:
ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz
This is the text "thisisaverysecretmessagethatisverysecureandsafe" that is "encrypted" through ROT-21 (half of 42). Your program, using the frequency table above, should be able to determine by how much each character was rotated and the original text.
(If you are not familiar with ROT-n, it is essentially shifting each character by n
. For example, in ROT-2, a -> c, b -> d, ..., x -> z, y -> a, z -> b
.)
How, you ask? The (very naive) algorithm you must use is:
- for each
n
from0
to25
inclusive, apply ROT--n
to the input string. (Negativen
because we want to reverse the encryption. ROT--n
is equivalent to ROT-26-n
, if that's any easier.) - convert each input string to a number by adding up the relative frequencies of the characters.
e
is0
,t
is1
,a
is2
, etc. For example, the corresponding number for the string"hello"
is 7 + 0 + 10 + 10 + 3 = 30. - find the string that has the lowest corresponding number.
- output that string and its corresponding
n
.
Rules:
- input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)
- you may use a different algorithm, as long as it always produces identical results. For example, having
z
be 0 ande
be 25 and choosing the highest number is also okay. - if two strings have identical scores, you can choose to output either one (or both) of them. This is an edge case and you do not have to account for it.
- this is code-golf, so the shortest code in bytes will win!
Test cases:
Input: ocdndnvqzmtnzxmzohznnvbzocvodnqzmtnzxpmzviynvaz
Output: 21 thisisaverysecretmessagethatisverysecureandsafe
Input: pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom
Output: 8 hellopeopleofprogrammingpuzzlescodegolfstackexchange
Input: ftueimeqzodkbfqpiuftdaffiqxhqeaufygefnqbqdrqofxkemrq
Output: 12 thiswasencryptedwithrottwelvesoitmustbeperfectlysafe
Input: jgtgkuvjghkpcnvguvecugvjcvaqwowuvfgetarv
Output: 2 hereisthefinaltestcasethatyoumustdecrypt
In case you were wondering, here is a JSFiddle of the JavaScript test code I wrote, which successfully decrypted all the test cases I threw at it.
wtaad
should give0 wtaad
as the result, andvszzc
should give25 wtaad
as the result. \$\endgroup\$