Skip to content

Instantly share code, notes, and snippets.

@ex
Created September 23, 2012 04:34
Show Gist options
  • Select an option

  • Save ex/3768883 to your computer and use it in GitHub Desktop.

Select an option

Save ex/3768883 to your computer and use it in GitHub Desktop.
Decrypt a message
// The text to decipher. It was created using a substitution cipher
var text = [[
Uid nx, aex jcdjipx iu wzux zp, ta wxtpa jtdaws, ai etkx vis.
Dcos zyexdzaxr aex Jxdw jezwipijes iu etkzyg nidx aety iyx hts
ai ri aex ptnx aezyg. Z zyexdzaxr aeta jezwipijes udin Wtdds Htww,
hei zp ns exdi tqactwws. Z htya ai ntfx Dcos cpxdp udxx. Z htya ai
gzkx aexn aex udxxrin ai qeiipx. Jxijwx tdx rzuuxdxya. Jxijwx qeiipx
rzuuxdxya qdzaxdzt. Oca zu aexdx zp t oxaaxd hts tniyg ntys
twaxdytazkxp, Z htya ai xyqicdtgx aeta hts os ntfzyg za qinuidatowx.
Pi aeta'p heta Z'kx adzxr ai ri.
Z htya ai piwkx jdiowxnp Z nxxa zy aex rtzws wzux os cpzyg qinjcaxdp,
pi Z yxxr ai hdzax jdigdtnp. Os cpzyg Dcos, Z htya ai qiyqxyadtax aex
aezygp Z ri, yia aex ntgzqtw dcwxp iu aex wtygctgx, wzfx patdazyg hzae
jcowzq kizr pinxaezyg pinxaezyg pinxaezyg ai pts, "jdzya exwwi hidwr."
Z vcpa htya ai pts, "jdzya aezp!" Z riy'a htya tww aex pcddicyrzyg
ntgzq fxshidrp. Z vcpa htya ai qiyqxyadtax iy aex atpf. Aeta'p aex otpzq
zrxt. Pi Z etkx adzxr ai ntfx Dcos qirx qiyqzpx tyr pcqqzyqa.
Scfzezdi Ntapcniai. (hhh.tdaznt.qin/zyak/dcos)
]]
// This is the frequency table of the language of the original text
// (from more frequent to less frequent).
var freqLang = "TEOIARNSHLMYUCWDGPFBVKJ"
// Create frequency table of the encrypted text.
var len = string.len(text)
var frequency = []
for (var k = 1; k <= len; k += 1) {
var c = string.upper(string.sub(text, k, k));
// Check if character is an uppercase letter.
if (string.find(c, "%u") != null) {
if (frequency[c] == null) {
frequency[c] = 1
}
else {
frequency[c] += 1
}
}
}
// Create table for sorting the text frequency.
var sortFreq = {}
for each (var k,v in pairs(frequency)) {
table.insert(sortFreq, {key: k, value: v})
}
// Sort in descending order.
table.sort(sortFreq, function(a, b) { return (a.value > b.value) })
// Create dictionary for deciphering.
var dic = {}
var freqText = ''
var index = 1
for each (var _,v in pairs(sortFreq)) {
freqText ..= v.key
dic[v.key] = string.sub(freqLang, index, index)
index += 1
}
// Deciphering text by replacing characters.
var decrypted = ''
for (var k = 1; k <= len; k += 1) {
var uppercase = false;
var c = string.sub(text, k, k)
if (string.find(c, "%u")) {
uppercase = true
}
else {
c = string.upper(c);
}
if (dic[c] != null) {
if (uppercase) {
decrypted ..= dic[c]
}
else {
decrypted ..= string.lower(dic[c])
}
}
else {
decrypted ..= c
}
}
print(decrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment