Skip to content

Instantly share code, notes, and snippets.

@topher6345
Last active August 29, 2015 14:22
Show Gist options
  • Save topher6345/f5efbb7135802de7358e to your computer and use it in GitHub Desktop.
Save topher6345/f5efbb7135802de7358e to your computer and use it in GitHub Desktop.
Caesar Cipher
# A library for encoding/cracking the Ceasar Cipher
module CaesarCipher
ALPHABET = ('a'..'z').to_a
ALPHABET_UPCASE = ('A'..'Z').to_a
# Responsible for encrypting a string
# using the Caesar Cipher
class Encoder
attr_reader :encoded_message
def initialize(plaintext:, shift:)
@words = plaintext.split(' ')
@cipher = Hash[*ALPHABET.zip(ALPHABET.rotate(shift)).flatten(1)].merge!(
Hash[*ALPHABET_UPCASE.zip(ALPHABET_UPCASE.rotate(shift)).flatten(1)])
apply_cipher
end
def apply_cipher
@encoded_message = @words.map do |word|
shift_letters_in_word(word)
end.join(' ')
end
def shift_letters_in_word(word)
word.split('').map do |letter|
cipher_letter(letter)
end.join('')
end
def cipher_letter(letter)
return @cipher[letter] if letter[/[a-zA-Z]/]
letter
end
end
# Responsible for cracking text
# encoded in a Cesar Cipher
class Cracker
attr_reader :cracked
def initialize(secret)
@secret = secret
@cracked = crack
end
def crack
CaesarCipher::Encoder.new(
plaintext: @secret, shift: calculate_offset
).encoded_message
end
def calculate_offset
ALPHABET.index('e') - ALPHABET.index(most_frequent_letter)
end
def most_frequent_letter
analyze_frequency.first[1]
end
def analyze_frequency
letters_by_count.map do |item|
["#{(item[0].to_f / total_count * 100.0).round(2)}%", item[1]]
end
end
def letters_by_count
count_letters.to_a.map(&:reverse).sort.reverse
end
def count_letters
@secret.split('').each_with_object(Hash.new(0)) do |letter, hsh|
hsh[letter.downcase] += 1 if letter[/[a-zA-Z]/]
end
end
def total_count
letters_by_count.inject(0) { |a, e| a + e[0] }
end
end
end
include CaesarCipher
plaintext = []
plaintext << <<TEXT
An online listing for a job at area marketing firm BizKo Solutions has left local man Ryan Urlich unsure whether he is truly dynamic enough to qualify for the position, sources confirmed Wednesday. “I’m willing to work in a fast-paced, deadline-oriented environment, sure, but am I really a dynamic self-starter?” said the 29-year-old college graduate, adding that this is the first time he’s ever considered whether he’s “a results-driven, high-energy ‘A’ player capable of providing cutting-edge insights.” “I suppose I can reimagine a brand, but can I go into a job interview, look someone in the eye, and tell them I’m a strong strategic thinker with the creative vision to drive brand awareness in an increasingly global marketplace? I don’t know if I can.” According to reports, Urlich ultimately decided not to apply for the job, saying he needed to take a few days to “really stop and think” about how dynamic he truly is so that he doesn’t waste anyone at BizKo’s time.
TEXT
plaintext << <<TEXT
Touting the product’s ability to combat common seasonal and year-round allergens, pharmaceutical manufacturer Bayer introduced Wednesday its new Claritin flamethrower capable of incinerating whatever is causing one’s allergies. “Our new flamethrower is proven to be effective at relieving itchy eyes, sneezing, and congestion by quickly and efficiently reducing dust mites, pollen, and other allergy-causing agents to smoldering ashes,” said company spokesperson Elaine Ferguson, adding that the product is available in either a regular 25-foot or an Extra Strength 50-foot jet of fire—ideal for eliminating ragweed, trees, grasses, and entire mold-ridden homes. “With this over-the-counter treatment, you can simply look at the latest allergy forecast, strap on the Claritin fuel pack, and wipe out allergy-inducing plants and pets without a hint of drowsiness.” Due to potential side effects, Ferguson cautioned that the Claritin flamethrower should never be combined with alcohol.
TEXT
plaintext << <<TEXT
Admitting that their behavior in previous years had left them embarrassed and ashamed, the nation’s dogs announced Thursday that they intend on keeping their shit together during this year’s Fourth of July fireworks displays. “Though we recognize we have not always demonstrated the most poise and self-control on this particular holiday, we want to assure everyone that this will finally be the year we don’t completely lose it and freak out upon hearing the booming of distant fireworks,” said Duchess, a 6-year-old cocker spaniel, adding that the country’s 80 million dogs aim to avoid cowering under the coffee table or uncontrollably urinating on the kitchen floor in a moment of pure panic after neighbors light off firecrackers or bottle rockets. “We’ve been preparing for the past few months, and we think we’ll finally be able to maintain our composure this time around. We can’t promise that we won’t whimper a little or try to jump up and sit next to you on the couch, but we’re definitely not going to sprint in circles around the living room or howl continuously until the noises stop.” The nation’s dogs concluded by acknowledging they could not guarantee that they won’t go completely apeshit the next time the doorbell rings.
TEXT
secret = Encoder.new(plaintext: plaintext.sample, shift: rand(3..25)).encoded_message
p secret
p Cracker.new(secret).cracked
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment