首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript -凯撒密码

JavaScript -凯撒密码
EN

Stack Overflow用户
提问于 2020-02-16 17:21:15
回答 2查看 1.9K关注 0票数 3

我知道过去有一些关于凯撒密码的帖子,我曾经看过,但是我没有找到一个帮助我解决这个问题的答案,因此我的帖子。

语言是JavaScript。我已经写了三个测试,其中两个已经通过了,但是第三个没有通过。我尝试使用嵌套的for循环循环遍历字母表和str,并对它们进行比较,然后根据数字上下移动字母索引,然后将字母推入一个新数组,并在最后返回已连接的数组。

它适用于正数,但不是负数。(我还应该指出,我还没有想过如何处理空间,我只想让它先用一个单词,然后从那里开始,谢谢!)

任何指向正确方向的指示都将不胜感激。

Kata指令:

函数caesarCipher应该接受一个字符串和一个数字(n),并返回一个新字符串,并应用凯撒密码。凯撒密码用不同的字母替换每一个明文字母,这是字母上下固定的位置。N表示应应用字母表的上下移位数。可能是消极的,也可能是积极的。

代码语言:javascript
复制
  E.g.
  caesarCipher('hello', 2)
    --> 'jgnnq'
  caesarCipher('hello world!', -3)
    --> 'ebiil tloia!'

我的测试:

代码语言:javascript
复制
const caesarCipher = require("../katas/caesar-cipher");
const { expect } = require("chai");

describe.only("caesarCipher", () => {
  it("returns an empty string when passed an empty string", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "";
    const num = 2;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "";
    expect(actualResults).to.equal(expectedResults);
  });
  it("returns a string with the letters replaced by the number of shifts up the alphabet", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "hi";
    const num = 2;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "jk";
    expect(actualResults).to.equal(expectedResults);
  });
  it("returns a string with the letters replaced by the number of shifts down the alphabet", () => {
    const alphabet = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z"
    ];
    const str = "dog";
    const num = -3;
    const actualResults = caesarCipher(alphabet, str, num);
    const expectedResults = "ald";
    expect(actualResults).to.equal(expectedResults);
  });
});

我的解决方案:

代码语言:javascript
复制
function caesarCipher(alphabet, str, num) {
  const strToArray = str.split("");
  console.log(strToArray);
  const cipheredStr = [];
  for (let i = 0; i < strToArray.length; i++) {
    for (let j = 0; j < alphabet.length; j++) {
      if (strToArray[i] === alphabet[j] && Math.sign(num) === 1) {
        console.log(Math.sign(num));
        cipheredStr.push(alphabet[(j += num)]);
      } else if (strToArray[i] === alphabet[j] && Math.sign(num) === -1) {
        console.log(Math.sign(num));
        console.log(alphabet[(j -= num)]);
        cipheredStr.push(alphabet[(j -= num)]);
      }
    }
  }
  console.log(cipheredStr.join(""));
  return cipheredStr.join("");
}

结果:

代码语言:javascript
复制
caesarCipher
[]

    ✓ returns an empty string when passed an empty string
[ 'h', 'i' ]
1
1
jk
    ✓ returns a string with the letters replaced by the number of shifts up the alphabet
[ 'd', 'o', 'g' ]
-1
g
-1
r
-1
j
jum
    1) returns a string with the letters replaced by the number of shifts down the alphabet


  2 passing (15ms)
  1 failing

  1) caesarCipher
       returns a string with the letters replaced by the number of shifts down the alphabet:

      AssertionError: expected 'jum' to equal 'ald'
      + expected - actual

      -jum
      +ald
      
      at Context.<anonymous> (spec/caesar-cipher.spec.js:108:30)
      at processImmediate (internal/timers.js:456:21)

EN

回答 2

Stack Overflow用户

发布于 2020-02-16 17:53:29

问题是,当num为负值时,您正在执行映射:

代码语言:javascript
复制
cipheredStr.push(alphabet[(j -= num)]);

num为阴性。当你减去一个负数时,你所做的就是增加它的绝对值。

相反,你应该这样做:

代码语言:javascript
复制
cipheredStr.push(alphabet[j + num]);

另外,请注意,要计算字母表中的索引,不需要将=放在其中。

Side notes

我知道你的解决方案是一项正在进行的工作。你必须考虑到:

  • ,当你把j + num和起来做翻译时,它超出了你的字母表的界限。同样的事情也可能发生在num.
  • In的负值问题的声明中,它声明caesarCipher只能接受两个参数,但是您将字母表作为第一个参数传递!

祝您的代码好运,并继续尝试:)

票数 1
EN

Stack Overflow用户

发布于 2022-06-07 06:10:34

代码语言:javascript
复制
let alphabets = 'abcdefghijklmnopqrstuvwxyz';
let arr = alphabets.split('')
// Cipher Get
function getCipher(str= alphabets, shift=3){
    return arr.reduce((a, c, i) => {
        let result = [...a]
        let tIndex = ( i + shift) % arr.length
        result[i]=arr[tIndex]
        return result;
    },[])
}

// Encrypt 
let stringToEnc = 'danger'
console.log('Plain Text -', stringToEnc)
let cipheredAlphabets = getCipher()
let encryptedStr = stringToEnc
    .toLowerCase()
    .split('')
    .map(function(p, i){
        let indexInAlphabets = arr.findIndex(c => p == c)
        return (cipheredAlphabets[indexInAlphabets])
    })
let encryptedText = encryptedStr.join('')
console.log('encrypted text - ', encryptedText)

// Decrypt
let cipherForDecrypt = getCipher(alphabets, -3)

let decryptedStr = encryptedText
    .toLowerCase()
    .split('')
    .map(function(p, i){
        let indexInAlphabets = cipheredAlphabets.findIndex(c => p == c)
        return (arr[indexInAlphabets])
    })
console.log('decrypted text - ', decryptedStr.join(''))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60251108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档