RosettaCodeData/Task/Bifid-cipher/EMal/bifid-cipher.emal
2026-04-30 12:34:36 -04:00

82 lines
2.4 KiB
Text

type PolybiusSquare
model
Map map
List grid
new by int side, text symbols
me.map ← text%Pair[]
me.grid ← List[].with(side, <int y|text[].with(side, <int x|""))
int y, x ← 0
for each text symbol in symbols
me.grid[y][x] ← symbol
me.map[symbol] ← int%int(y ⇒ x).named("y", "x")
x++
if x æ side
x ← 0
y++
end
end
end
fun asText ← text by block
text result
for int y ← 0; y < me.grid.length; y++
for int x ← 0; x < me.grid[y].length; x++
result.append(" " + me.grid[y][x])
end
result.appendLine()
end
return result
end
end
type BifidCipher
model
PolybiusSquare square
new by PolybiusSquare ←square do end
fun encrypt ← text by text value
List row ← int[].with(value.length * 2)
int y ← 0
int x ← value.length
for each text char in value
Pair p ← me.square.map[char]
row[y++] ← p.y
row[x++] ← p.x
end
text encrypted
for int i ← 0; i < row.length; i += 2
encrypted.append(me.square.grid[row[i]][row[i + 1]])
end
return encrypted
end
fun decrypt ← text by text value
List row ← int[]
for each text char in value
Pair p ← me.square.map[char]
row.append(p.y)
row.append(p.x)
end
int y ← 0
int x ← value.length
text decrypted
for int i ← 0; i < value.length; i++
decrypted.append(me.square.grid[row[y++]][row[x++]])
end
return decrypted
end
end
type Main
List pairs ← Pair[
text%PolybiusSquare("ATTACKATDAWN" ⇒ PolybiusSquare(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ")).named("sample", "square"),
text%PolybiusSquare("FLEEATONCE" ⇒ PolybiusSquare(5, "BGWKZQPNDSIOAXEFCLUMTHYVR")).named("sample", "square"),
text%PolybiusSquare("ATTACKATDAWN" ⇒ PolybiusSquare(5, "BGWKZQPNDSIOAXEFCLUMTHYVR")).named("sample", "square"),
text%PolybiusSquare("The invasion will start on the first of January".upper().replace(" ", "") ⇒
PolybiusSquare(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")).named("sample", "square")]
for each Pair pair in pairs
writeLine("Using Polybius square:")
write(pair.square)
BifidCipher cipher ← BifidCipher(pair.square)
write("Encrypting '", pair.sample, "'")
text encrypted ← cipher.encrypt(pair.sample)
write(" ⇒ '", encrypted, "'")
text decrypted ← cipher.decrypt(encrypted)
writeLine(" ⇒ '", decrypted, "'")
writeLine()
end