Created
September 12, 2013 21:56
-
-
Save bjhaid/6544406 to your computer and use it in GitHub Desktop.
Chicago Ruby hack night puzzle http://www.puzzlenode.com/puzzles/12-secret-messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CaesarCipher | |
attr_accessor :shift_value | |
def initialize(shift_value) | |
@shift_value = shift_value | |
@shifted_alphabet_array = ("A".."Z").to_a.rotate(@shift_value) | |
@alphabet_array = ("A".."Z").to_a | |
end | |
def cipher(text) | |
text.upcase.split("").each_with_object("") do |chr, cipher_text| | |
cipher_text << @shifted_alphabet_array[@alphabet_array.index(chr)] | |
end | |
end | |
def decipher(ciphered_text) | |
ciphered_text.upcase.split("").each_with_object("") do |chr, decipher_text| | |
decipher_text << @alphabet_array[@shifted_alphabet_array.index(chr)] | |
end | |
end | |
end | |
class VigenereCipher | |
def initialize(key) | |
@key = random_shift_value(key) | |
end | |
DICTIONARY = "/usr/share/dict/words" | |
def dictionary_lookup(text) | |
File.readlines(DICTIONARY).select { |word| word if (word.chomp.downcase == text.downcase) }.first | |
end | |
def random_shift_value(text) | |
[*0..25].each do |shift_value| | |
caesar_cipher_instance = CaesarCipher.new(shift_value) | |
deciphered_text = caesar_cipher_instance.decipher(text) | |
return deciphered_text if dictionary_lookup(deciphered_text) | |
end | |
end | |
def compacted_decipher(word) | |
word = word.gsub(/\W/,"").split(" ").join("") | |
keys = @key.downcase.split("").each_with_object([]) { |chr,keys_array| keys_array << ("a".."z").to_a.index(chr) } | |
keys_mulitplier = (word.split("").size / keys.size) + 1 | |
keys = keys * keys_mulitplier | |
word.downcase.split("").zip(keys).each_with_object("") do |kchar, deciphered_word| | |
deciphered_word << character(ciphered_alphabet_array(kchar[1]).index(kchar[0])) | |
end | |
end | |
def decipher(word) | |
compacted_word = compacted_decipher(word) | |
word.split("").each_with_index do |character, index| | |
(compacted_word.insert(index, character)) if character.match(/\W/) | |
end | |
compacted_word.upcase | |
end | |
def ciphered_alphabet_array(shift_value) | |
("a".."z").to_a.rotate(shift_value) | |
end | |
def character(index) | |
("a".."z").to_a[index] | |
end | |
end | |
vigenere_cipher = VigenereCipher.new("RLCOPY") | |
word = "IONDVQY DZH QNTY KLQRY BVISEK TYHME JERWLF; ZHV YEYOAEW RRBEI WEFZE FI HRGTY EYG UNTH. SS GLC WLR COEGIEY TYDX V EEK KEIK HVDVQ, OT JHIZY TF PI ZUSK VXEGNXH XUGT DHR FNOLOH SKAI; VIRONX WLNZ DVDXU, G NVFIFYAIB IAJ, WZOP PUMV ZLRT IK ZMYR CFPI." | |
deciphered_word = vigenere_cipher.decipher(word) | |
p deciphered_word | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment