Last active
August 29, 2015 13:56
-
-
Save elreimundo/9177109 to your computer and use it in GitHub Desktop.
A solution to a Caesar cipher challenge in which only letters are offset and in which spaces are a handful of special characters; the original challenge featured only lowercase letters and an offset of four, but this is intended to scale easily.
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 north_korean_cipher message, offset = 4 | |
unexaggerate message.chars.map{|char| decode char, offset}.join('') | |
end | |
def unexaggerate message | |
message.gsub(/\d+/) { |num| num.to_i / 100 } | |
end | |
def decode char, offset | |
case | |
when lowercase?(char) then shift_by offset, char, 'a' | |
when uppercase?(char) then shift_by offset, char, 'A' | |
when space?(char) then ' ' | |
else char | |
end | |
end | |
def shift_by offset, char, base_char, alphabet_length = 26 | |
((char.ord - base_char.ord - offset) % alphabet_length + base_char.ord).chr | |
end | |
def lowercase? char | |
'a' <= char && 'z' >= char | |
end | |
def uppercase? char | |
lowercase? char.downcase | |
end | |
def space? char | |
'@#$%^&*'.include? char | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment