跳至主要内容

[刷題紀錄] Codewars-5kyu

TL;DR

Others

ROT13(凱薩加密法的一種)

  • url:https://www.codewars.com/kata/530e15517bc88ac656000716/train/javascript
  • description:ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher. Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string, they should be returned as they are. Only letters from the latin/english alphabet should be shifted, like in the original Rot13 "implementation".
    const chai = require("chai");
    const assert = chai.assert;

    describe("Tests", function() {
    it("Sample tests", function() {
    for (const [input, expected] of [["test", "grfg"], ["Test", "Grfg"]]) {
    assert.strictEqual(rot13(input), expected, `Test failed with messsage = '${input}'`);
    }
    });
    });

After practice

只有想到暴力解的解法,所以詢問GPT幫忙解答一下

GPT提供的寫法
function rot13(str) {
return str.replace(/[a-zA-Z]/g, function(c) {
var base = c <= 'Z' ? 65 : 97;
return String.fromCharCode((c.charCodeAt(0) - base + 13) % 26 + base);
});
}

GPT的解法:

這個程式使用 ROT13 加密方法對給定的字符串進行加密。讓我們一步步解釋程式的內容:

  1. /[a-zA-Z]/g 正規表達式: 這個正規表達式會匹配字符串中的所有字母,不論大小寫。 [a-zA-Z] 表示匹配任何一個字母。 g 修飾符表示全局匹配,即匹配所有符合條件的子字符串。

  2. function(c) 匿名函數: 這是一個在 replace 方法中用於替換匹配字符串的函數。 c 是匹配到的每個字符。

  3. 字符編碼轉換: 對於大寫字母,它們的字符編碼範圍是 65 到 90(A 到 Z)。 對於小寫字母,它們的字符編碼範圍是 97 到 122(a 到 z)。 在加密過程中,我們需要將字符從其 ASCII 編碼值轉換為對應的 ROT13 加密後的編碼值。 加密過程中,我們通過減去基礎值(65 或 97)來將字母字符轉換為 0 到 25 之間的數字,再加 13(ROT13 加密的偏移量),再取模 26(保證在字母範圍內循環)。 最後,我們將加密後的數字重新轉換為字符編碼,並通過 String.fromCharCode() 方法將其轉換為字符。

  4. return 語句: 這個匿名函數返回了加密後的字符。

  5. str.replace() 方法: 這個方法用於替換字符串中匹配到的部分。 在這裡,我們用加密後的字符替換了原始字符串中的字符。