LoginSignup
4
2

More than 5 years have passed since last update.

js シーザー暗号(ROT13)

Last updated at Posted at 2016-12-24

お題

アルファベットに対してのシーザー暗号(ROT13)の関数をつくる

*シーザー暗号 Wikipedia
シーザー暗号は単一換字式暗号の一種で、平文の各文字を、辞書順に3文字分シフトして暗号文を作る暗号。現代でもシフト数を13にした方式としてROT13が使用されることがある。

script.js
function rot13(str) {
//write your code
}
rot13("URYYB JBEYQ!");

出力結果 例

script.js
("SERR CVMMN!") // "FREE PIZZA!"
("SERR YBIR?") // "FREE LOVE?"
("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.") // "THE QUICK BROWN DOG JUMPED OVER THE LAZY FOX."

主に使ったもの

charCodeAt()
fromCodeAt
map()
split()
join()
ASCII

考え方

・split()で文字列を一文字切り離す。
・切り離した文字ひとつひとつにmap()で同様の処理を繰り返す。
・処理する文字を変数に入れて、大文字のアルファベットであるかどうか判定する。
 ASCIIにて、Aは65、Zは90。(x < 65 || x > 90)
 当てはまらないものはfromCodeAtで返す。
・大文字のアルファベットで
 (x < 78)はfromCodeAtで+13して返す。
残りはfromCodeAtで-13して返す。
・最後にjoin('')で一緒にしておわり。

コード

script.js
function rot13(str) {
  return str.split('')
    .map.call(str, function(char) {
      x = char.charCodeAt(0);
      if (x < 65 || x > 90) {
        return String.fromCharCode(x);  
      }
      else if (x < 78) {
        return String.fromCharCode(x + 13);
      }
      return String.fromCharCode(x - 13);
    }).join('');  
}
rot13("SERR PBQR PNZC");

大文字小文字対応のコード

function rot13(str) {
  var i =[]; 
  i = str.split('');
  return i.map.call( i,function(char) {
      x = char.charCodeAt(0);
      if ((65 <= x && x < 78) || (97 <= x && x < 110)) {
        return String.fromCharCode(x + 13);
      }
      else if ((78 <= x && x <= 90) || (110 <= x && x <= 122) ) {
              return String.fromCharCode(x - 13);
      }
    return String.fromCharCode(x);  
    }).join('');  
}
rot13("Uryyb Jbeyq!");

正規表現を使ったコード


function rot13(str) { 
  return str.replace(/[A-Z]/g, (L) => String.fromCharCode(65 + (L.charCodeAt(0) - 65 + 13) % 26));
}

他にもコードが浮かんだ方、コメントお待ちしてます。

4
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2