Skip to content

Instantly share code, notes, and snippets.

@saxxi
Last active August 29, 2015 14:27
Show Gist options
  • Save saxxi/058b62a4c3be0c28e95c to your computer and use it in GitHub Desktop.
Save saxxi/058b62a4c3be0c28e95c to your computer and use it in GitHub Desktop.
class CaesarCypher
# https://en.wikipedia.org/wiki/Letter_frequency
CHAR_DISTRIBUTION = {'a'=>8.167,'b'=>1.492,'c'=>2.782,'d'=>4.253,'e'=>12.702,'f'=>2.228,'g'=>2.015,'h'=>6.094,'i'=>6.966,'j'=>0.153,'k'=>0.772,'l'=>4.025,'m'=>2.406,'n'=>6.749,'o'=>7.507,'p'=>1.929,'q'=>0.095,'r'=>5.987,'s'=>6.327,'t'=>9.056,'u'=>2.758,'v'=>0.978,'w'=>2.361,'x'=>0.150,'y'=>1.974,'z'=>0.074}
IDEAL_ORDER = Hash[CHAR_DISTRIBUTION.sort_by { |_, v| -v }].keys
THRESHOLD_PERCENTAGE = 10
def encode(message, shift)
message.chars.map do |char|
if char =~ /[a-z]/
encode_char char, shift, 97
elsif char =~ /[A-Z]/
encode_char char, shift, 65
else
char
end
end.join('')
end
def decode(message, shift)
encode(message, -shift)
end
def decode_guess(message)
guesses = {}
25.times do |shift|
test_decode = decode message, shift
letters = letters_order_by_count(test_decode)
guesses[shift] = similarity_index(letters)
end
decode message, guesses.max_by{|k,v| v}[0]
end
private
def encode_char(char, shift, ascii_diff)
((char.ord - ascii_diff + shift) % 26 + ascii_diff).chr
end
def letters_order_by_count(message)
letters = count_letters(message)
total = letters.values.inject(0, :+).to_f
letters.each do |letter, count|
letters[letter] = count / total * 100
end
Hash[letters.sort_by { |_, v| -v }].keys
end
def count_letters(message)
letters_only = message.downcase.gsub /[^a-zA-Z]/, ''
Hash[letters_only.split('').group_by{|x| x}.map{|k,v| [k,v.count] }]
end
# IDEAL_ORDER = ["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"]
# letters = ["e", "n", "a", "t", "i", "o", "s", "r", "d", "l", "h", "c", "u", "p", "m", "y", "g", "w", "f", "b", "v", "k", "x", "j", "q"]
def similarity_index(letters)
matches = 0
letters.each_with_index do |char, i|
position_percentage = letters.find_index(char) / 26.0 * 100
ideal_position_percentage = IDEAL_ORDER.find_index(char) / 26.0 * 100
if (ideal_position_percentage - position_percentage).abs < THRESHOLD_PERCENTAGE
matches += 1
end
end
matches
end
end
caesar_cypher = CaesarCypher.new
original = "汉语 Aa - Village did removed enjoyed explain nor ham saw calling talking. Securing as informed declared or margaret. Joy horrible moreover man feelings own shy. Request norland neither mistake for yet. Between the for morning assured country believe. On even feet time have an no at. Relation so in confined smallest children unpacked delicate. Why sir end believe uncivil respect. Always get adieus nature day course for common. My little garret repair to desire he esteem.
On projection apartments unsatiable so if he entreaties appearance. Rose you wife how set lady half wish. Hard sing an in true felt. Welcomed stronger if steepest ecstatic an suitable finished of oh. Entered at excited at forming between so produce. Chicken unknown besides attacks gay compact out you. Continuing no simplicity no favourable on reasonably melancholy estimating. Own hence views two ask right whole ten seems. What near kept met call old west dine. Our announcing sufficient why pianoforte.
Dissuade ecstatic and properly saw entirely sir why laughter endeavor. In on my jointure horrible margaret suitable he followed speedily. Indeed vanity excuse or mr lovers of on. By offer scale an stuff. Blush be sorry no sight. Sang lose of hour then he left find.
Yet remarkably appearance get him his projection. Diverted endeavor bed peculiar men the not desirous. Acuteness abilities ask can offending furnished fulfilled sex. Warrant fifteen exposed ye at mistake. Blush since so in noisy still built up an again. As young ye hopes no he place means. Partiality diminution gay yet entreaties admiration. In mr it he mention perhaps attempt pointed suppose. Unknown ye chamber of warrant of norland arrived.
In as name to here them deny wise this. As rapid woody my he me which. Men but they fail shew just wish next put. Led all visitor musical calling nor her. Within coming figure sex things are. Pretended concluded did repulsive education smallness yet yet described. Had country man his pressed shewing. No gate dare rose he. Eyes year if miss he as upon.
Barton waited twenty always repair in within we do. An delighted offending curiosity my is dashwoods at. Boy prosperous increasing surrounded companions her nor advantages sufficient put. John on time down give meet help as of. Him waiting and correct believe now cottage she another. Vexed six shy yet along learn maids her tiled. Through studied shyness evening bed him winding present. Become excuse hardly on my thirty it wanted.
That know ask case sex ham dear her spot. Weddings followed the all marianne nor whatever settling. Perhaps six prudent several her had offence. Did had way law dinner square tastes. Recommend concealed yet her procuring see consulted depending. Adieus hunted end plenty are his she afraid. Resources agreement contained propriety applauded neglected use yet.
Agreed joy vanity regret met may ladies oppose who. Mile fail as left as hard eyes. Meet made call in mean four year it to. Prospect so branched wondered sensible of up. For gay consisted resolving pronounce sportsman saw discovery not. Northward or household as conveying we earnestly believing. No in up contrasted discretion inhabiting excellence. Entreaties we collecting unpleasant at everything conviction.
Now for manners use has company believe parlors. Least nor party who wrote while did. Excuse formed as is agreed admire so on result parish. Put use set uncommonly announcing and travelling. Allowance sweetness direction to as necessary. Principle oh explained excellent do my suspected conveying in. Excellent you did therefore perfectly supposing described.
Whole every miles as tiled at seven or. Wished he entire esteem mr oh by. Possible bed you pleasure civility boy elegance ham. He prevent request by if in pleased. Picture too and concern has was comfort. Ten difficult resembled eagerness nor. Same park bore on be. Warmth his law design say are person. Pronounce suspected in belonging conveying ye repulsive.
Was justice improve age article between. No projection as up preference reasonably delightful celebrated. Preserved and abilities assurance tolerably breakfast use saw. And painted letters forming far village elderly compact. Her rest west each spot his and you knew. Estate gay wooded depart six far her. Of we be have it lose gate bred. Do separate removing or expenses in. Had covered but evident chapter matters anxious.
Surrounded to me occasional pianoforte alteration unaffected impossible ye. For saw half than cold. Pretty merits waited six talked pulled you. Conduct replied off led whether any shortly why arrived adapted. Numerous ladyship so raillery humoured goodness received an. So narrow formal length my highly longer afford oh. Tall neat he make or at dull ye. He an thing rapid these after going drawn or. Timed she his law the spoil round defer.
In surprise concerns informed betrayed he learning is ye. Ignorant formerly so ye blessing. He as spoke avoid given downs money on we. Of properly carriage shutters ye as wandered up repeated moreover. Inquietude attachment if ye an solicitude to. Remaining so continued concealed as knowledge happiness. Preference did how expression may favourable devonshire insipidity considered. An length design regret an hardly barton mr figure.
Conveying or northward offending admitting perfectly my. Colonel gravity get thought fat smiling add but. Wonder twenty hunted and put income set desire expect. Am cottage calling my is mistake cousins talking up. Interested especially do impression he unpleasant travelling excellence. All few our knew time done draw ask. Certainty determine at of arranging perceived situation or. Or wholly pretty county in oppose.
Favour met itself wanted settle put garret twenty. In astonished apartments resolution so an it. Unsatiable on by contrasted to reasonable companions an. On otherwise no admitting to suspicion furniture it. Woody equal ask saw sir weeks aware decay. Entrance prospect removing we packages strictly is no smallest he. For hopes may chief get hours day rooms. Oh no turned behind polite piqued enough at.
Forbade few through inquiry blushes you. Cousin no itself eldest it in dinner latter missed no. Boisterous estimating interested collecting get conviction friendship say boy. Him mrs shy article smiling respect opinion excited. Welcomed humoured rejoiced peculiar to in an. Up am intention on dependent questions oh elsewhere september. No betrayed pleasure possible jointure we in throwing. And can event rapid any shall woman green.
Hope they dear who its bred. Smiling nothing affixed he carried it clothes calling he no. Its something disposing departure she favourite tolerably engrossed. Truth short folly court why she their balls. Excellence put unaffected reasonable mrs introduced conviction she. Nay particular delightful but unpleasant for uncommonly who. Carried nothing on am warrant towards. Polite in of in oh needed itself silent course.
Assistance travelling so especially do prosperous appearance mr no celebrated. Wanted easily in my called formed suffer. Songs hoped sense as taken ye mirth at. Believe fat how six drawing pursuit minutes far. Same do seen head am part it dear open to. Whatever may scarcely judgment had. Inquietude simplicity terminated she compliment remarkably few her nay. The weeks are ham asked jokes. Neglected perceived shy nay concluded.
Not mile draw plan snug next all. Houses latter an valley be indeed wished merely in my. Money doubt oh drawn every or an china. Visited out friends for expense message set eat. Much did had call new drew that kept. Limits expect wonder law she. Now has you views woman noisy match money rooms. To up remark it eldest length oh passed. Off because yet mistake feeling has men. Consulted disposing to moonlight ye extremity."
encoded = caesar_cypher.encode original, 3
puts "Original: #{original}"
puts '-----'
puts "Encoded: #{encoded}"
puts '-----'
puts "Decoded: #{caesar_cypher.decode encoded, 3}"
puts '-----'
puts "Guessed: #{caesar_cypher.decode_guess encoded}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment