Last active
February 17, 2018 09:32
-
-
Save ryanveroniwooff/6124388431c03cb36db09a5b64495c87 to your computer and use it in GitHub Desktop.
simple string encoding from key
This file contains 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
def encode(message, key) | |
c = key.to_s.split('').map { |e| e.to_i }.cycle #setup key cycle | |
letter_hash = Hash[('a'..'z').zip(1..26)] #hash containing 'a' => 1, 'b' => 2, and so on... | |
message.split('').map { |e| letter_hash.fetch(e,e) + c.next} #encode vlaues | |
end | |
def decode(code, key) | |
c = key.to_s.split('').map { |e| e.to_i }.cycle #setup key cycle | |
h = Hash[(1..26).zip('a'..'z')] #hash containing 1 => 'a', 2=> 'b', and so on... | |
code.map { |e| h.fetch((e - c.next),e) }.join('') # decode and fetch values from hash and join | |
end | |
# encode("masterpiece", 1939) | |
# m a s t e r p i e c e | |
# 13 1 19 20 5 18 16 9 5 3 5 | |
# + 1 9 3 9 1 9 3 9 1 9 3 | |
# -------------------------------- | |
# 14 10 22 29 6 27 19 18 6 12 8 | |
# - 1 9 3 9 1 9 3 9 1 9 3 | |
# -------------------------------- | |
# 13 1 19 20 5 18 16 9 5 3 5 | |
# m a s t e r p i e c e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment