How Knowing About ASCII Code Allows us to Create Caesar Cyphers Easily
Vijay Kumar
Full Stack Developer | Big Data Enthusiast | PHP | Python | E-Learning Developer
In Caesar cyphers we have to change the value of a character by shifting it forward by a certain number of digits. So the character 'a' when cyphered becomes 'd' if it's moved forward by 3 characters. One way to perform this operation while not using ASCII code would be to keep a list/array of all the English language characters and use a loop to find out which character is X number of characters ahead of another.
But by using ASCII code we can simply convert a character to its ASCII equivalent by using an inbuilt function and add the number of digits it needs to be moved ahead by. Then we can convert the ASCII code back to it's English character equivalent by using a similar inbuilt function.
Here's an example of doing so to solve a Codechef problem by using PHP...
In PHP we can use the ord() and chr() functions to get the ASCII code and the character equivalent of it.
Brief description:
A total number of Q test cases is given. In each test case N is the length of the string. S is the initial string. T is the cyphered string. U needs to be cyphered the same way that T is cyphered. Print the cyphered version of the string U.
Problem statement:
Problem solution:
领英推荐
Solution code:
<?php
$q = readline();
for($i = 0; $i < $q; $i++) {
$n = readline();
$s = readline();
$t = readline();
$u = readline();
$diff = ord($t[0]) - ord($s[0]);
if($diff < 0) {
$diff += 26;
}
$new_str = "";
for($j = 0; $j < $n; $j++) {
$new_ord = ord($u[$j]) + $diff;
if($new_ord > 122) {
$new_ord = 96 + ($new_ord - 122);
}
$new_str .= chr($new_ord);
}
print($new_str . PHP_EOL);
}
Solution Explanation:
Observation 1:
Since the character is always shifted down the alphabet, the character of the string which has the cypher applied on it will be greater than the corresponding character of the first string.
If we do get a negative number, it means that the shifting of characters needs to be wrapped around the last character 'z'.
Since there are 26 characters in the English language, we can do so by adding 26 to the previously calculated negative difference.
Observation 2:
While calculating the shifted value of the alphabet, If the value is greater than 122 or the ASCII equivalent of 'z', then we need to wrap the shifted alphabet past z.
This is achieved by adding the difference between the ASCII value of the shifted alphabet and 122.
Approach: