Caesar Cipher

HackerRank 問題: Caesar Cipher

Question

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar’s cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

  • Original alphabet: abcdefghijklmnopqrstuvwxyz
  • Alphabet rotated +3: defghijklmnopqrstuvwxyzabc

HackerRank 問題: Caesar Cipher

Answer

<?php

/*
 * Complete the 'caesarCipher' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts following parameters:
 *  1. STRING s
 *  2. INTEGER k
 */

function caesarCipher($original_sentence, $cipher_offset_number) {
    // set cipher offset mapping list
    $offset_letter_code_list = [];
    for ($initial_code = 0; $initial_code < 26; $initial_code++) {
        $cipher_code = $initial_code + $cipher_offset_number;
        $offset_letter_code_list[] = $cipher_code % 26;
    }

    // set alphabet cipher mapping
    $alphabet_cipher_mapping = [];
    foreach ($offset_letter_code_list as $initial_code => $cipher_code) {
        // find upper and lower case initial and cipher ascii code
        $upper_case_initial_ascii_code = $initial_code + 65;
        $lower_case_initial_ascii_code = $initial_code + 97;
        $upper_case_cipher_ascii_code = $cipher_code + 65;
        $lower_case_cipher_ascii_code = $cipher_code + 97;

        // transfer ascii to letter
        $upper_case_key = chr($upper_case_initial_ascii_code);
        $upper_case_cipher_value = chr($upper_case_cipher_ascii_code);
        $lower_case_key = chr($lower_case_initial_ascii_code);
        $lower_case_cipher_value = chr($lower_case_cipher_ascii_code);

        // set mapping alphabet cipher mapping table
        $alphabet_cipher_mapping[$upper_case_key] = $upper_case_cipher_value;
        $alphabet_cipher_mapping[$lower_case_key] = $lower_case_cipher_value;
    }

    // cipher sentence
    $length_of_original_sentence = strlen($original_sentence);

    $cipher_sentence = '';
    for ($check_index = 0; $check_index < $length_of_original_sentence; $check_index++) {
        $letter = $original_sentence[$check_index];
        // default is not cipher
        $cipher_letter = $letter;
        if (isset($alphabet_cipher_mapping[$letter])) {
            // if there is cipher letter exist, then cipher it
            $cipher_letter = $alphabet_cipher_mapping[$letter];
        }
        $cipher_sentence.=$cipher_letter;
    }

    return $cipher_sentence;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$s = rtrim(fgets(STDIN), "\r\n");

$k = intval(trim(fgets(STDIN)));

$result = caesarCipher($s, $k);

fwrite($fptr, $result . "\n");

fclose($fptr);

Reference