Last active
August 29, 2015 14:00
-
-
Save s-mage/11263514 to your computer and use it in GitHub Desktop.
Two-square cipher in ruby (https://en.wikipedia.org/wiki/Two-square_cipher).
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
require 'matrix' | |
class TwoSquare | |
attr_accessor :first_square, :second_square | |
ALPHABET = 'йцукенгшщзхъэждлорпавыфячсмитьбю.,- '.split('') | |
def initialize | |
@first_square = build_square | |
@second_square = build_square | |
end | |
def build_square | |
alphabet = ALPHABET.shuffle.each_slice(6).to_a | |
Matrix[*alphabet] | |
end | |
def encode_text(string) | |
string.chars.each_slice(2). | |
map { |(x, y)| encode(x, y) }. | |
flatten.join | |
end | |
alias_method :decode_text, :encode_text | |
def encode(first, second) | |
first_coors = first_square.index first | |
second_coors = second_square.index second | |
first_encoded = first_square[first_coors[0], second_coors[1]] | |
second_encoded = second_square[second_coors[0], first_coors[1]] | |
[first_encoded, second_encoded] | |
end | |
alias_method :decode, :encode | |
end | |
cypher = TwoSquare.new | |
test_string = 'съешь ка еще этих французских булок, да выпей чаю.' | |
encoded = cypher.encode_text test_string | |
decoded = cypher.decode_text encoded | |
puts test_string | |
puts encoded | |
puts decoded |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment