Last active
November 26, 2015 17:18
-
-
Save mkweick/75cd7813523958c379ed to your computer and use it in GitHub Desktop.
Simple Cipher
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 Cipher | |
VALUES = [('a'..'z').to_a, (0..25).to_a].transpose.to_h | |
attr_reader :key | |
def initialize(key = new_key) | |
@key = key | |
raise_error_conditions | |
end | |
def encode(msg) | |
secure(msg) | |
end | |
def decode(msg) | |
secure(msg, nil) | |
end | |
private | |
def new_key | |
100.times.map { ('a'..'z').to_a.sample }.join | |
end | |
def raise_error_conditions | |
invalid = ('A'..'Z').to_a + ('0'..'9').to_a | |
if invalid.any? { |char| key.include? char } || key.empty? | |
raise ArgumentError, "Key can't be empty or contain invalid characters." | |
end | |
end | |
def secure(msg, encode_flag=1) | |
message = '' | |
index = 0 | |
while index < msg.length | |
distance = encode_or_decode_msg(msg, index, encode_flag) | |
letter = distance % VALUES.keys.count | |
message += VALUES.key(letter) | |
index += 1 | |
end | |
message | |
end | |
def encode_or_decode_msg(msg, index, encode_flag) | |
if encode_flag | |
VALUES[msg[index]].to_i + VALUES[key[index]].to_i | |
else | |
VALUES[msg[index]].to_i - VALUES[key[index]].to_i | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment