One simple way to encrypt a string is to “rotate” every alphanumeric character by a certain amount. Rotating a character means replacing it with another character that is a certain number of steps away in normal alphabetic or numerical order.For example, if the string “Zebra-493?” is rotated 3 places, the resulting string is “Cheud-726?”. Every alphabetic character is replaced with the character 3 letters higher (wrapping around from Z to A), and every numeric character replaced with the character 3 digits higher (wrapping around from 9 to 0). Note that the non-alphanumeric characters remain unchanged.Given a string and a rotation factor, return an encrypted string.
Signature
string rotationalCipher(string input, int rotationFactor)
Input
1 <= |input| <= 1,000,000 0 <= rotationFactor <= 1,000,000
Output
Return the result of rotating input a number of times equal to rotationFactor.
Example 1
input = Zebra-493? rotationFactor = 3 output = Cheud-726?
Example 2
input = abcdefghijklmNOPQRSTUVWXYZ0123456789 rotationFactor = 39 output = nopqrstuvwxyzABCDEFGHIJKLM9012345678
function rotationalCipher($input, $rotation_factor) {
for($i=0; $i< 26;$i++) {
$letter = chr(97 + $i);
$alphabetMap[$letter] = $i;
}
$newString = '';
$input = str_split($input);
foreach ($input as $item) {
#Da
//Sanity Check
if(!ctype_alpha($item) && !is_numeric($item))
{
$newString .= $item;
}
//if character
if(ctype_alpha($item))
{
#item D;a
$initialstateUpperCase = false;
if (ctype_upper($item)) {
$initialstateUpperCase = true; #D
$item = strtolower($item); #d
}
$value = $alphabetMap[$item]; #3;0
$newValue = $value + $rotation_factor; #5;2
if($newValue > 26) {
$newValue = $newValue % 26;
}
$newCharacter = array_search($newValue, $alphabetMap); #f;c
if($initialstateUpperCase === true)
{
$newCharacter = strtoupper($newCharacter); #F
}
$newString .= $newCharacter; #Fc
}
//if integer
if(is_numeric($item))
{
$newValue = $item + $rotation_factor;
if($newValue > 10) {
$newValue = $newValue % 10;
}
$newString .= $newValue;
}
}
return $newString;
}