どうも、試験問題文で日本特有言い回しでブチ切れ寸前のFlaxBearです。
今回も、以前書いた暗号解読辞典に書かれている暗号をプログラムにしてみようと思います。思った以上に難しかったorz
#
# 幾何学暗号を行い、5文字ずつに区切って出力する
# @param [String] plainText 平文
# @return [Array] 幾何学暗号
def basicGeometryCipher(plainText)
chipherText = "" # 暗号文
count = 0 # 平文の指定に使用
blankPlainText = plainText.gsub(" ", "") # 単語間の空白を取り除く
textSize = blankPlainText.length # 平文の文字数
# 平文の文字数が奇数の場合足して偶数にする
if textSize % 2 == 1 then
textSize += 1
end
# マトリクスの入れ子を作成
#matrixList = Array.new(textSize/2, Array.new(2)) これはエラーにはならないが不具合を起こし、正しい書き方ではない
matrixList = Array.new(textSize/2).map{Array.new(2,"")}
# マトリクスに平文の文字を入れていく
for matrixList_y in 0..1 do
for matrixList_x in 0..(textSize/2)-1 do
matrixList[matrixList_x][matrixList_y] = blankPlainText[count]
count += 1
end
end
# マトリクスの一番上から二文字ずつ取っていき暗号文を作成する
for matrixList_x in 0..(textSize/2)-1 do
chipherText += matrixList[matrixList_x].join
end
return chipherText.scan(/.{1,#{5}}/) # 5文字単位で区切る
end
#
# 幾何学暗号を、平文に戻す
# @param [Array] cipherTextList 暗号文
# @return [String] 平文
def basicGeometryDecryption(cipherTextList)
plainText = "" # 平文
count = 0 # 平文の指定に使用
chipherText = cipherTextList.join # 5文字単の配列なのでまとめる
chipherTextSize = chipherText.length # 暗号文の文字数
# 平文の文字数が奇数の場合足して偶数にする
if chipherTextSize % 2 == 1 then
chipherTextSize += 1
end
# マトリクスの入れ子を作成
matrixList = Array.new(chipherTextSize/2).map{Array.new(2,"")}
# マトリクスに暗号文の文字を入れていく
for matrixList_x in 0..(chipherTextSize/2)-1 do
for matrixList_y in 0..1 do
matrixList[matrixList_x][matrixList_y] = chipherText[count]
count += 1
end
end
# マトリクスから文字を取り出していく
for matrixList_y in 0..1 do
for matrixList_x in 0..(chipherTextSize/2)-1 do
plainText += matrixList[matrixList_x][matrixList_y]
end
end
# マトリクスの一番上から二文字ずつ取っていき暗号文を作成する
for matrixList_x in 0..(textSize/2)-1 do
chipherText += matrixList[matrixList_x].join
end
return plainText
end
プログラムはコメントを読めばわかると思います(解説放り投げ)。しかし、
matrixList = Array.new(textSize/2, Array.new(2))
matrixList = Array.new(textSize/2).map{Array.new(2,"")}
これがかなり難点でしたorz最初は上の方を書いていたんですけど、全ての配列が連動して入っていてずっと頭の中で?マークが出ていたんですけど調べてみたら下を書かないといけないみたいですね。
参考先
最後に、ルート転置型幾何学暗号のプログラムで凄まじく悩んでいますので、若干間が開くかもしれないです