Skip to content

Instantly share code, notes, and snippets.

@durrellchamorro
Created May 5, 2016 20:21
Show Gist options
  • Save durrellchamorro/2e6db155ea78e0cd35dadda028a76954 to your computer and use it in GitHub Desktop.
Save durrellchamorro/2e6db155ea78e0cd35dadda028a76954 to your computer and use it in GitHub Desktop.
Crypto Square
class Crypto
def initialize(text)
@text = text
end
def normalize_plaintext
@text.gsub(/\W/,'').downcase
end
def size
Math.sqrt(normalize_plaintext.length).ceil
end
def plaintext_segments
segments = []
normalized = normalize_plaintext
until normalized.empty?
segments << normalized.slice!(0...size)
end
segments
end
def ciphertext
segments = plaintext_segments
ciphered = ''
segments.length.times do
segments.each do |seg|
ciphered << seg.slice!(0)
if seg.empty?
seg << '*'
end
end
end
ciphered.delete('*')
end
def normalize_ciphertext
result = []
l = plaintext_segments.map(&:length).max
transposed = plaintext_segments.map(&:chars).map{|e| e.values_at(0...l)}.transpose
transposed.each { |array| result << array.compact.join}
result.join(' ')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment