javascript - 如何处理凯撒密码 (Javascript) 中的负移位

标签 javascript caesar-cipher

我正在尝试通过 Odin Projects Caesars Cipher,测试要求能够转换负移位。根据我当前的代码,我可以转换小写,但我在 B 或 W 方面遇到一些问题。

it('works with negative shift', function() {
    expect(caesar('Mjqqt, Btwqi!', -5)).toEqual('Hello, World!');

但是返回时我的代码会吐出

'Hello, =orld!'

如此接近!我一直在试图弄清楚它是什么,但我不确定我在这里做错了什么,因为“H”正在工作

我已经多次重写了这个东西,但我总是到这里。我确信这只是一个数字之类的。然而,这超出了我目前所知或所能理解的范围。

提前感谢大家,对于这么简单的问题深表歉意。

const caesar = function(message, shift) {
    return message 
    .split("") //splits it into an array
    .map(message => { //does the following to each element in the array
        normalStr = String.fromCharCode(message.charCodeAt())
        prePoint = message.charCodeAt() //gets the charcode of element  
    //if/else checks to see if upper or lower case
    if (prePoint >= 65 && prePoint <= 90) { //upper case
        return String.fromCharCode(((prePoint - 65 + shift) % 26) + 65);
    } else if (prePoint >= 97 && prePoint <= 122){ //lower case
        return String.fromCharCode((prePoint -97 + shift % 26) + 97) 
    }  else {
        return normalStr

        //1 func proc uppoer case
        //1 func proc lowercase
        //1 func proc non upper/lower case
    }})
    .join("")

}

最佳答案

您的代码仅适用于正凯撒转变,因为在
String.fromCharCode(((prePoint - 65 + shift) % 26) + 65);
prePoint - 65 + shift 可能低于零(使用 prePoint = B = 66 且 shift = -5 你会得到 - 4)

您可以通过检查 (prePoint - 65 + shift) 的结果是否为负来解决此问题,如果是,则添加 26:

let newPoint = (prePoint - 65 + shift) % 26;
if(newPoint < 0) newPoint += 26;
return String.fromCharCode(newPoint + 65);

(小写字母也一样)

或者,您可以在函数开始时将负偏移转换为正偏移(-5 凯撒偏移与 21 凯撒偏移相同):

if(shift < 0) { shift = 26 + (shift % 26);}

完整示例:

function caesar(message, shift) {
  if (shift < 0) {
    shift = 26 + (shift % 26);
  }
  return message
    .split("") //splits it into an array
    .map(message => { //does the following to each element in the array
      normalStr = String.fromCharCode(message.charCodeAt())
      prePoint = message.charCodeAt() //gets the charcode of element  
      //if/else checks to see if upper or lower case
      if (prePoint >= 65 && prePoint <= 90) { //upper case
        return String.fromCharCode(((prePoint - 65 + shift) % 26) + 65);
      } else if (prePoint >= 97 && prePoint <= 122) { //lower case
        return String.fromCharCode(((prePoint - 97 + shift) % 26) + 97)
      } else {
        return normalStr;
      }
    })
    .join("");
}

console.log(caesar('Mjqqt, Btwqi!', -5)); // Hello World!

关于javascript - 如何处理凯撒密码 (Javascript) 中的负移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57294167/

相关文章:

javascript - amp-script 未找到脚本哈希。 amp-脚本[脚本 ="hello-world"]

javascript - 使用 jQuery 的简单 AJAX HTTP GET

凯撒密码重复字母

c - 使用 cs.50.h 中的 `string` 的 C 代码中的段错误

打开 Intranet 网站无法正常工作时,Internet Explorer 11 上的 Javascript window.open()

php - 如何使用 jquery 或 css 在 wordpress 中隐藏类别标题或描述?

c - 打印字符数组时显示未知字符

java - 使用java解密凯撒密码

java - 在java中输出文本文件的CaesarCipher程序

javascript - react 单行组件