Skip to content

Instantly share code, notes, and snippets.

@AaronRandall
Last active October 20, 2016 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AaronRandall/02845db55a4af14fec9d to your computer and use it in GitHub Desktop.
Save AaronRandall/02845db55a4af14fec9d to your computer and use it in GitHub Desktop.
ciphertexts = [
"VGYURYPEDFNCEPGEWELLPVNWRDCNFGMGXQEPPRG-CBFIGLEMG",
"EQ’PMEIGQNVBAGBTFEGMSYNRKMNWEPBLWBYPSNWMQNFBDWEQVYNR-CBFIGLEMG"
]
english_freqs = "ETAOINSHRDLCUMWFGYPBVKJXQZ".chars
# count letter frequencies in ciphertexts
char_freqs = Hash.new(0)
(ciphertexts.join).each_char {|c| char_freqs[c] += 1}
# sort by letter frequency freqs (descending)
ciphertext_freqs = Hash[char_freqs.sort_by{|k,v| -v}]
# remove non-alphanumeric ciphertext chars (e.g. punctuation)
(ciphertext_freqs.keys - english_freqs).each {|p| ciphertext_freqs.delete(p)}
# display the letter and frequency mappings
puts "Ciphertext => English (count)"
ciphertext_freqs.each_with_index do |ct_freq,index|
puts "#{ct_freq.first} => #{english_freqs[index]} (#{ct_freq.last})"
end
used_english_freqs = english_freqs[0..ciphertext_freqs.count-1].join
cipher_char_freqs = ciphertext_freqs.keys.join
ciphertexts.each do |ciphertext|
ciphertext_before = ciphertext
ciphertext_after = ciphertext.tr(cipher_char_freqs, used_english_freqs)
puts "Ciphertext before: #{ciphertext_before}"
puts "Ciphertext after: #{ciphertext_after}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment