Created
October 10, 2013 17:35
-
-
Save SimplGy/6922370 to your computer and use it in GitHub Desktop.
Ruby Implementation of a Rotational Cipher. Wrote in https://coderpad.io/966172
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
$ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
$alphabet = 'abcdefghijklmnopqurstvwxyz' | |
# Get an index of an alphabetic letter based on the index and offset | |
def calculateOffset(index, offset) | |
index += offset | |
index -= 26 while index >= 26 # keep subtracting until we get to the right range | |
index | |
end | |
# Get a char from the alphabet based on an offset | |
def getCharByOffset(char, offset=0) | |
# Chars could be in the upper alphabet, the lower alphabet, or neither. | |
indexUpper = $ALPHABET.index(char) | |
indexLower = $alphabet.index(char) | |
if indexUpper | |
i = calculateOffset(indexUpper, offset) | |
char = $ALPHABET[i].chr # Get the char at that index | |
elsif indexLower | |
i = calculateOffset(indexLower, offset) | |
char = $alphabet[i].chr | |
end | |
char | |
end | |
# Rotationally encode a string | |
def rotx(x, string, encrypt=true) | |
newString = '' | |
x = -x unless encrypt | |
# for each char in the string | |
string.each_char do |char| | |
# TODO: support decryption | |
newString << getCharByOffset(char, x) | |
end | |
# get a new char that is `x` away in the alphabet | |
newString | |
end | |
# ------------------------------------------------ Assertions | |
puts rotx 10, 'Hello, World' | |
# => "Rovvy, Gybvn" # Shouldn't this be "Rovvy, Gycvn"? | |
puts rotx 10, 'Rovvy, Gycvn', false | |
# => "Hello, World" | |
# Rotation numbers greater than 26 should work as well | |
puts rotx 36, 'Hello, World' | |
# => "Rovvy, Gybvn" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment