rot13.js

Codewars 알고리즘 풀이


Problem

  • ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet.
    • ROT13은 알파벳 13 글자로 대체되는 글자 대체 암호(letter substitution cipher)이다.
  • ROT13 is an example of the Caesar cipher.
    • ROT13은 Caesar cipher의 예이다.
  • Create a function that takes a string and returns the string ciphered with Rot13.
    • 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.
    • 라틴/영어 알파벳의 글자만 대체한다.



Solution 01

function rot13(str) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const cipher = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
  
  return str.split('').map(i => {
    if (alphabet.indexOf(i) < 0) {
      return i;
    }
    
    return cipher[alphabet.indexOf(i)];
  }).join('');
}

rot13('grfg');  // test
rot13('Grfg');  // Test
rot13('Pbqr');  // Code
rot13('jnef');  // wars


Solution 02

function rot13(str) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const cipher = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
  
  return str.replace(/[a-z]/gi, i => cipher[alphabet.indexOf(i)]);
}

rot13('grfg');  // test
rot13('Grfg');  // Test
rot13('Pbqr');  // Code
rot13('jnef');  // wars


Solution 03

function rot13(str) {
  const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLM';
  
  return str.replace(/[a-z]/gi, i => alphabet[alphabet.indexOf(i) + 13]);
}

rot13('grfg');  // test
rot13('Grfg');  // Test
rot13('Pbqr');  // Code
rot13('jnef');  // wars