Created
July 9, 2013 23:17
-
-
Save tahb/5962174 to your computer and use it in GitHub Desktop.
Transposition Decrypter
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 transposition_decrypter(key) | |
# Calculate the length of columns based on the message length and how many letters in this key attempt | |
col_length = (@encrypted_message.length) / key | |
answer = [] | |
group_count = 0 | |
groups = {} | |
# Create character groups for each column + 1 so we start at 1 for readability | |
(key + 1).times do |n| | |
groups.merge!({n => [] }) | |
end | |
# Split all characters into groups of the pre determined col_length using modulo, associated with their group number. | |
# The first group of 168 chars have group number 1. When the chars index gets to 168, start adding the chars to the next group. | |
# Going along until all chars are grouped by their columns. In this case evenly with no remainder. | |
@encrypted_message.chars.each_with_index do |char, index| | |
if index.modulo(col_length) == 0 | |
group_count = group_count + 1 | |
end | |
groups[group_count] << char | |
end | |
# As each group has an even amount of chars, we can iterate over that many times (168). Each iteration pulls out the same char from each group, adding it to the answer which at the end is the answer. | |
col_length.times do |i| | |
(key + 1).times do |j| | |
answer << groups[j][i] | |
end | |
end | |
answer | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment