首页 > 解决方案 > 这个 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} `;
  }
}

标签: javascriptpythonencryption

解决方案


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);
}

推荐阅读