ภาพรวม
Atbash Cipher คือรหัสลับแบบแทนที่ (substitution cipher) ที่แมปตัวอักษรแต่ละตัวเป็นตัวอักษรตรงข้ามในอัลฟาเบท: a↔z, b↔y, c↔x, ..., m↔n
ตัวอย่าง
"abcdefg" → "zyxwvut"
"hello" → "svool"
หลักการ
ASCII('a') = 97, ASCII('z') = 122
N = 97 + 122 = 219
ตัวอักษร c → ตัวใหม่ = chr(N - ord(c))
เช่น 'a' (97) → chr(219-97) = chr(122) = 'z'
โค้ด Python
class Solution:
def solve(self, text):
N = ord('z') + ord('a')
return "".join(chr(N - ord(c)) for c in text)
ob = Solution()
print(ob.solve("abcdefg"))
print(ob.solve("hello"))
ขยาย: รองรับตัวใหญ่-เล็ก
def atbash(text):
result = []
for c in text:
if c.islower():
result.append(chr(ord('z') - (ord(c) - ord('a'))))
elif c.isupper():
result.append(chr(ord('Z') - (ord(c) - ord('A'))))
else:
result.append(c)
return "".join(result)
ผลลัพธ์
zyxwvut svool