方阵密码通过改变字符的排列与读取顺序隐藏文本。它先把文字按行排入矩形,再沿列读取。
任务说明
实现一种经典的秘密消息编码方式:方阵密码。
给定英文文本,输出编码结果。
首先规范化输入:删除空格和标点,字母全部转为小写。
然后把字符分成若干行,换行后形成一个矩形。
例如,下句:
"If man was meant to stay on the ground, god would have given us roots."
规范化后为:
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots"
明文应排列成尽可能接近正方形的矩形,大小由消息长度决定。
设列数为 c、行数为 r,选择满足以下条件的最小整数 c:
r * c >= 消息长度。c >= r。c - r <= 1。
示例规范化后有 54 个字符,因此取 c = 8、r = 7:
"ifmanwas"
"meanttos"
"tayonthe"
"groundgo"
"dwouldha"
"vegivenu"
"sroots "
从左到右,逐列自上而下读取,得到密文。
上面的消息编码为:
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
按 c 组、每组长度 r 输出,用空格分隔,使其仍能组成完整矩形。若距离填满矩形少 n 个字符,在最后 n 组末尾各补一个空格。
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau "
把这些组叠起来,就能直观看出如何还原原消息:
"imtgdvs"
"fearwer"
"mayoogo"
"anouuio"
"ntnnlvt"
"wttddes"
"aohghn "
"sseoau "