Affine
0 comments
function encode(string $text, int $num1, int $num2): string{
$res = "";
$alphabet = range('a', 'z');
$lowerString = strtolower($text);
$counter = 0;
if(!isGcd($num1, 26)){throw new Exception();}
foreach (str_split($lowerString) as $char){
if(in_array($char, $alphabet)){
$index = array_search($char, $alphabet);
$enc = ($num1 * ($index) + $num2) % 26;
$enc = ($enc +26) % 26;
$res.= $alphabet[$enc];
}
else if (ctype_digit($char)){
$res.= $char;}
else{continue;}
$counter++;
if($counter === 5){
$res.= ' ';
$counter = 0;}
}
return trim($res);
}
function isGcd($a, $m){
while($m != 0){
$temp = $m;
$m = $a % $m;
$a = $temp;
}
return $a===1;
}
function mmi($a){
$m =26;
for($i=0; $i<$m; $i++){
if(($a * $i) % $m === 1){
return $i;
}
}
}
function decode(string $text, int $num1, int $num2): string{
if(!isGcd($num1, 26)){throw new Exception();}
$noSpaces = str_replace(' ', '', $text);
$res = "";
$alphabet = range('a', 'z');
foreach (str_split($noSpaces) as $char){
if(in_array($char, $alphabet)){
$index = array_search($char, $alphabet);
$dec = (mmi($num1)*($index - $num2)) % 26;
$dec = ($dec +26) % 26;
$res.= $alphabet[$dec];
}
else {$res.= $char;}
}
return $res;
}
Comments