javascript - 这个 Python 函数可以转换为 Javascript 吗?
问题描述
我正在使用密码;加密和解密,我目前正在使用现代拉丁字母的Polybius 密码。例如,字母“a”是两位数代码,“11”和“abc”是“11 12 13”。
我在 Python 中找到了一个解决方案:
# Python Program to implement polybius cipher
# function to display polybius cipher text
def polybiusCipher(s):
# convert each character to its encrypted code
for char in s:
# finding row of the table
row = int((ord(char) - ord('a')) / 5) + 1
# finding column of the table
col = ((ord(char) - ord('a')) % 5) + 1
# if character is 'k'
if char == 'k':
row = row - 1
col = 5 - col + 1
# if character is greater than 'j'
elif ord(char) >= ord('j'):
if col == 1 :
col = 6
row = row - 1
col = col - 1
print(row, col, end ='', sep ='')
我正在尝试转换它并在NaN
我滥用某些东西或多种东西时不断得到它。这是我到目前为止所拥有的:
function polybius(input, encode = true) {
for (let i = 0; i < input.length; i++) {
let letter = input[i];
let row = letter.charCodeAt(0 - letter.charCodeAt(97)) / 5 + 1;
let col = letter.charCodeAt(0 - (letter.charCodeAt(97) % 5)) + 1;
if (letter.charCodeAt(0) === letter.charCodeAt(107)) {
row = row - 1;
col = 5 - col + 1;
} else if (letter.charCodeAt(0) >= letter.charCodeAt(106)) {
if (col === 1) {
col = 6;
row = row - 1;
}
col = col - 1;
}
return `${row}${col} `;
}
}
解决方案
let row = letter.charCodeAt(i - letter.charCodeAt('a')) / 5 + 1;
不正确,因为字母本身的字符代码是letter.charCodeAt(0)
,而字符代码'a'
是'a'.charCodeAt(0)
。此外,您需要使用Math.floor
向下舍入。
因此,它应该是let row = Math.floor((letter.charCodeAt(0) - 'a'.charCodeAt(0)) / 5) + 1;
。
初始化有类似的问题,col
应该是let col = (letter.charCodeAt(0) - 'a'.charCodeAt(0)) % 5 + 1;
。
接下来,检查字母是否为k
,无需比较 char 码,可以直接使用letter === 'k'
. 比较看字母是否大于等于'j'
,也有类似的问题,可以直接使用>= 'j'
。
最后,您在循环的第一次迭代中返回,因此它只会运行一次。相反,您可以构建一个字符串以在最后输出或返回。
function polybius(input, encode = true) {
let str = '';
for (let i = 0; i < input.length; i++) {
let letter = input[i];
let row = Math.floor((letter.charCodeAt(0) - 'a'.charCodeAt(0)) / 5) + 1;
let col = (letter.charCodeAt(0) - 'a'.charCodeAt(0)) % 5 + 1;
if (letter === 'k') {
row = row - 1;
col = 5 - col + 1;
} else if (letter >= 'j') {
if (col === 1) {
col = 6;
row = row - 1;
}
col = col - 1;
}
str += `${row}${col} `;
}
console.log(str);
}
推荐阅读
- javascript - 当客户端按下按钮时,是否可以在 HTML 浏览器的根目录中更新 .txt 文件?
- c# - 从 HTML 表中提取带有标题的数据
- apache-spark - Spark 在不同的列上多次加入相同的数据集
- node.js - 从 AWS Lambda 函数的 [ List ] DynamoDB 项目中查询
- c# - 在场景加载中保持不同的 PhotonView
- swift - 多个用户访问相同的用户默认数据 Swift
- python - 将 dict 理解转换为正常形式
- java - 将数据插入数据库时出现“org.springframework.beans.ConversionNotSupportedException”错误
- python - 表单字段输入的Python Django长度为1,即使它为空
- c# - Blazor:无法获取以对象为键的字典