euler/ruby/euler059.rb

33 lines
797 B
Ruby

require_relative 'euler'
def input
File.readlines("../input/p059.txt")[0].split(',').map(&:strip).map(&:to_i).map(&:chr).join
end
def xor_encrypt(string, key)
key_bytes = key.split('').map(&:ord)
string.split('').map(&:ord).each_with_index.map do |byte, i|
byte^key_bytes[i % 3]
end.map(&:chr).join
end
def xor_decrypt(string, key)
key_bytes = key.split('').map(&:ord)
string.split('').map(&:ord).each_with_index.map do |encrypted_byte, i|
encrypted_byte^key_bytes[i % 3]
end.map(&:chr).join
end
def find_key
("aaa".."zzz").each do |key|
decrypted = xor_decrypt(input, key)
if decrypted.count(' ') > 100 and decrypted.scan(/\ the\ /).length > 5
return key
end
end
end
def solution
xor_decrypt(input, find_key).split('').map(&:ord).inject(:+)
end