私はどのようにalgosに:私はcacar暗号


どのように私はアルゴスに反応する


今日、我々はシーザー暗号の上に行きます.またはcypher ...または暗号?🤔
どのようなシーザー暗号はとにかく何ですか?さて、私はしましょうWikipedia その問題について説明してください.

In cryptography, a Caesar cipher ... is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.


私たちの目標は、この暗号を使用してメッセージをエンコードすることです!私たちがこのalgoの上でさらに行く前に、私はこのシリーズの前の記事を指摘したいです:



  • 今、我々はどのように我々のソリューションにRactoを使用して取得する方法についての迅速な要約.

    これは


    Reactoは、この問題を解決するために使用するメソッドを表す頭字語です.として、これらはステップです:

  • 再出発

  • 例:例

  • Aアプローチ

  • Cコード

  • T :テスト

  • 最適化
  • 🏁 始めましょう!

    プロンプト


    Create a function that will receive a string message and a key number as input and return an encoded version of the message. A message is encoded by replacing each letter in the message with the letter that is a specified number (the key argument) of letters before it in the alphabet. When shifting, if the selection goes beyond the first letter of the alphabet you should continue counting from the last letter of the alphabet. Encoded messages should be returned in all upper case.


    プロンプトを再表示する


    ここでは、我々はプロンプトのメモを作ることができると私たち自身の言葉でそれを再構築します.私は実際に上記のプロンプトを崇拝したので、私は通常、私は通常の方法で以下のようにそれを知らせます.
    /* 
    R: Restate
    
    Create a function that takes two args: a string and a number.
    Return an encoded version of the string in all upper case.
    In order to encode the string, each letter needs to be shifted by the number argument.
    While shifting, if we need to go left of the first letter in the alphabet we should wrap to the last letter of the alphabet.
    */
    
    明確な質問

    Q: Might the function receive non-letter characters?
    A: Yes, the function may receive non-letter characters. Only letters will be shifted, keep other character in places.

    Q: Will the input string always be all caps?
    A: The input string may be in lower or upper case or a mix of both.


    そうだね、それはクリアされて、メモのプロンプトの再声明に加えられます:
    /* 
    R: Restate
    
    Create a function that takes two args: a string and a number.
    Return an encoded version of the string in all upper case.
    In order to encode the string, each letter needs to be shifted by the number argument.
    While shifting, if we need to go left of the first letter in the alphabet we should wrap to the last letter of the alphabet.
    Non-letter characters should not be altered.
    */
    

    例:例


    この節では、期待される戻り値の例をいくつか作成する必要があります.例は提供されなければなりません、そして、我々は常に明確化のためにより多くを加えることができます.まず最初の例を引っ張りますWikipedia article on Caesar Cipher .
    // example 1
    
    > message = "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG";
    > key = 3;
    
    > caesarCipher(message, key);
    
    QEB NRFZH YOLTK CLU GRJMBA LSBO QEB IXWV ALD
    
    // example 2
    
    > message2 = "Have you ever heard of The Byzantine Generals problem?";
    > key2 = 19;
    
    > caesarCipher(message2, key2);
    
    OHCL FVB LCLY OLHYK VM AOL IFGHUAPUL NLULYHSZ WYVISLT?
    
    // example 3
    
    > message3 = "They saw about 5 wolves circling the field!";
    > key3 = 99;
    
    > caesarCipher(message3, key3);
    
    YMJD XFB FGTZY 5 BTQAJX HNWHQNSL YMJ KNJQI!
    
    
    私たちは多くの例を考え出すことができました、しかし、これは現在良いです.間隔と句読点が保存されていることがわかります.

    Aアプローチ


    コーディングする前に、解決策を見つけるためのアプローチを通して考えるのがベストでしょう.最初のステップは確かに2つの引数を取る関数を作成することです.他に何か
    私は、プロンプトの再声明の下のコメントでアプローチを書きます.あなたのアプローチを書いて、あなたのソリューションをコーディングする次のステップに移動する前に数回編集することがあります.
    関数では、アルファベットのすべての文字を順番に保持する文字列を作成します.
    /*
    A: Approach
    
    - create function caesarCipher(message, key)
    
    - create constant for alphabet characters, all caps
    */
    
    アルファベットの大文字の場合は、メッセージの文字と一致するように簡単になります.メッセージの文字が小文字であったとしても、メッセージ文字列を反復処理する前に、これらの文字を大文字に変換します.また、入力文字列を反復処理する際にエンコードされたメッセージを生成するアキュムレータを設定する必要があります.
    /*
    A: Approach
    
    - create function caesarCipher(message, key)
    
    - create constant for alphabet characters, all caps
    - create variable for the return string value (encoded message)
    - convert input string to upper case
    */
    
    これは、私が以前に言及していたものをもたらします、我々は入力ストリングの上で反復する必要があります.各イテレーションを使用して、入力文字列の現在の文字を取得し、アルファベット定数と比較することで文字をチェックする必要があります.文字が定数であるならば、それは手紙です.文字が文字でない場合は、エンコードされたメッセージに追加し、入力文字列の次の文字に移動します.文字が手紙であるならば、我々はより多くの仕事をする必要があります.
    /*
    A: Approach
    
    - create function caesarCipher(message, key)
    
    - create constant for alphabet characters, all caps
    - create variable for the return string value (encoded message)
    - convert input string to upper case
    - iterate over input string
    -- create constant for the current character
    -- check if current character is a letter
    --- if character is not a letter, add it to the encoded message without change
    --- else if char is a letter ....?
    */
    
    文字が文字の場合はどうすればよいですか?あなたはアルファベットでその文字のインデックスを取得し、入力キー番号と組み合わせる必要があります.ので、現在の文字のインデックスを取得しますが、関数の2番目の引数であるキー値をどのように使用しますか?
    キーはシフト数であり、プロンプト状態はアルファベットを下に動かすkey 回数.我々にキーがあるならば3 現在の文字はD , エンコードされた文字はA . 登場人物D アルファベットの4番目の文字はインデックス3です.キーで3 , 私たちは3 - 3 = 0 , そして、インデックス0の文字はA . So D であろうA キーが3ならば.
    以下に、あなたが3で左に暗号文字列を回転させる場合は、プレーンアルファベットで終わることがわかります.それは呼び出しのようです.shift() 暗号が配列であれば3回、同じ配列の末尾にシフト文字を追加します.
    ┌────────┬─────────────────────────────────────────────────────┐
     plain   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 
    ├────────┼─────────────────────────────────────────────────────┤
     cipher  X Y Z A B C D E F G H I J K L M N O P Q R S T U V W 
    └────────┴─────────────────────────────────────────────────────┘
    
    暗号は、プレーンアルファベットをシフトして作成され、アルファベットの暗号化テキストをシフトすることによって再現されます.
    コードに戻りましょう!我々は現在の文字の現在のインデックスからキーを引く必要があるということを知っています、しかし、新しいインデックスのために負の数を生成するならば、どうですか?これらのケースを扱うために、我々はアルファベットで文字の量を考慮する必要があります.アルファベットで26文字がありますので、インデックスは0から25までの範囲です.我々が0を下回るならば、我々は我々がアルファベットのもう一方の端を包むことができることを確認する必要があります.我々の出発点がそうであるならば0 インデックスとキーは3 , 私たちの新しい位置は-3 . 新しい位置は以下です0 我々は、最後のインデックスから戻る必要があります知っている.25 , 3回.我々がそうするならば、それは新しい位置を作ります22 , または文字W , 私たちが意図するより1つ少ないインデックスです.インデックスを0から数え始めるので、26文字で25文字があるからです.それで、我々はAを加えなければなりません1 それがゼロ未満であるならば、新しい位置に、残りの部分をこの新しい位置を26で割ることから得てください.残りの数値は負になり、最後のインデックスの数に追加できます.25 , 更新された新しい位置に到達する23 , またはX .
    /*
    A: Approach
    
    - create function caesarCipher(message, key)
    
    - create constant for alphabet characters, all caps
    - create variable for the return string value (encoded message)
    - convert input string to upper case
    - iterate over input string
    -- create constant for the current character
    -- check if current character is a letter and get the index of that letter in the alphabet
    --- if character is not a letter, add it to the encoded message without change
    --- else if character is a letter, subtract the key value from its alphabet index to get the index of the substitute character (encoded character)
    ---- if the new index is less than 0, the value should instead be the value of the remainder from new index +1 divided by 26 plus 25
    */
    
    新しいインデックスが0未満で、残りのためにモジュロ演算を実行するならば、我々のアプローチの最後のステップは否定的な数で我々を残します.それで、私たちがその負の剰余を25(アルファベットのインデックスの数)に加えるならば、我々は最後のインデックスから後方に数えることによって、適切な手紙を得ます.このように、どんなに鍵が大きいとしても、我々はまだ我々の手紙を得ます.プログラミングでは、我々は実際には、第0のインデックスとラッピングを考慮する必要が回転する文字ホイールを持っていません!
    一旦我々がこの新しいインデックス位置を持つならば、我々はアルファベットから対応する手紙をつかむことができて、我々が機能の終わりに戻るコード化されたメッセージにそれを加えることができます.それから、我々はコード化されたメッセージを返すかもしれなくて、されるかもしれません!
    これは最新のアプローチです.
    /*
    A: Approach
    
    - create function caesarCipher(message, key)
    
    - create constant for alphabet characters, all caps
    - create variable for the return string value (encoded message)
    - convert input string to upper case
    - iterate over input string
    -- create constant for the current character
    -- check if current character is a letter and get the index of that letter in the alphabet
    -- IF character is a letter:
    --- subtract the key value from current character's index to get the index of the substitute character (encoded character)
    --- IF the index for the substitute character is less than 0:
    ---- the value for the substitute's index should instead be 25 plus the remainder of this index+1 and 26
    --- get the substitute character at this new index from the alphabet constant and add it to the encoded message
    -- ELSE if character is not a letter, add it to the encoded message without change
    - return the encoded message
    */
    

    Cコード


    コードへの時間!🧑‍💻
    これは非常に長い記事がまだ我々のアプローチはとても簡単です!ガイドとして役立つ機能にアプローチコメントを貼り付けることで、行動に計画を立てましょう.
    あなたがこれを把握するためにいくつかの時間を取るしたい場合はこれ以上スクロールしないでください!そうでない場合は、準備ができているとスポイラーの準備をスクロールしてください!
    // - create function caesarCipher(message, key)
    function caesarCipher(message, key) {
      // - create constant for alphabet characters, all caps
      const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
      // - create variable for the return string value (encoded message)
      let secret = "";
      // - convert input string to upper case
      message = message.toUpperCase();
    
      // - iterate over input string
      for (let i = 0; i < message.length; i++) {
        // -- create constant for the current character
        let char = message[i];
    
        // -- check if current character is a letter and get the index of that letter in the alphabet
        let pos = alphabet.indexOf(char);
    
        // -- IF character is a letter:
        if (pos > -1) {
          // --- subtract the key value from current character's index to get the index of the substitute character (encoded character)
          let newPos = pos - key;
    
          // --- IF the index for the substitute character is less than 0:
          if (newPos < 0) {
            // ---- the value for the substitute's index should instead be 25 plus the remainder of this index+1 and 26
            newPos = 25 + (newPos + 1) % 26;
          }
    
          // --- get the substitute character at this new index from the alphabet constant and add it to the encoded message
          let newChar = alphabet[newPos];
          secret += newChar;
    
          // -- ELSE if character is not a letter, add it to the encoded message without change
        } else {
          secret += char;
        }
      }
      // - return the encoded message
      return secret;
    }
    
    そして、ここではコメントなしの関数です.
    function caesarCipher(message, key) {
      const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      let secret = "";
      message = message.toUpperCase();
      for (let i = 0; i < message.length; i++) {
        let char = message[i];
        let pos = alphabet.indexOf(char);
        if (pos > -1) {
          let newPos = pos - key;
          if (newPos < 0) {
            newPos = 25 + (newPos + 1) % 26;
          }
          let newChar = alphabet[newPos];
          secret += newChar;
        } else {
          secret += char;
        }
      }
      return secret;
    }
    
    私は、メソッドの使用を指摘する瞬間を取るindexOf() . 引数に与えられた文字が対象の文字列または配列で見つかったインデックスの値を返します.文字が文字列でない場合、メソッドは戻ります-1 . したがって、このメソッドは-1 それは手紙だと思う.

    T :テスト


    エキサイティングな部分は、コードにアプローチを翻訳しています.楽しい部分は、コードをテストしています!私がいくつかのテストをしたところで、下記のCodepenを見てみましょう.
    🎉! 我々は再び自分のテストに合格!いいね我々は今この機能を最適化するいくつかの考えを与える必要があります.

    最適化


    アルファベットの上を行くことは常に入力文字列の大きさに関係なく定数になるでしょう.ただし、入力文字列と同じサイズの新しい文字列を作成します.message = message.toUpperCase() . 私は非常に大きな入力文字列を想像することができますこれは問題になります.上のケースのバージョンが全体の文字列を大文字にすることなくマッチするかどうかチェックするだけです.私はこの種の変化のために時間をしました、そして、それはより遅く行くようでした.私はいくつかの詳細については、この記事に従ってそれについて話をしなければならない、またはこのセクションを更新します.入力文字列全体にループを行い、メッセージ内のすべての文字を訪問する必要があるため、常に発生します.これにより、時間の複雑さがo ( n )のままであることを知っています.スペースの複雑さは同じです.だから、今ではアルファベットを一定のオブジェクトにすることを除いて、今のところ私にとって明らかな最適化はありません.この上に任意の入力がある場合は以下のコメントをください!

    次は何ですか。


    次に、我々は行く

    ありがとう


    もう一度、このポストを読むためにあなたの日から時間をとってくれてありがとう.私についてdev.to あなたがこれのようなより多くの内容を見たいならば.まわりで会いましょう!