Created
August 8, 2019 14:44
-
-
Save skalibog/815ea9c8f616870c7396b03652ccda64 to your computer and use it in GitHub Desktop.
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
# ruby 2.6.3 | |
# | |
class Crypto | |
def initialize(method, string, count) | |
@method = method | |
@string = string | |
@count = count | |
end | |
def call | |
return @string if @string.nil? || @string.empty? || @count <= 0 | |
case @method | |
when 'encrypt' | |
p encrypt | |
when 'decrypt' | |
p decrypt | |
else | |
raise ArgumentError.new("Method must be in %w[encrypt decrypt]") | |
end | |
end | |
private | |
def encrypt | |
result = @string | |
@count.times do |_| | |
odd = '' | |
even = '' | |
result.split('').each_with_index do |letter, index| | |
index.even? ? odd << letter : even << letter | |
end | |
result = odd + even | |
end | |
result | |
end | |
def decrypt | |
length = @string.length.even? ? @string.length / 2 : @string.length / 2 + 1 | |
result = @string | |
@count.times do |_| | |
odd = result[0...length] | |
even = result[length..] | |
result = '' | |
length.times do |index| | |
result << odd[index] << even[index] | |
end | |
end | |
result | |
end | |
end | |
Crypto.new("encrypt", "abcdefghij", 1).call | |
Crypto.new("decrypt", "acegibdfhj", 1).call | |
Crypto.new("encrypt", "abcdefghij", 2).call | |
Crypto.new("decrypt", "aeidhcgbfj", 2).call | |
Crypto.new("encrypt", "abcdefghij", 3).call | |
Crypto.new("decrypt", "aihgfedcbj", 3).call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment