Created
July 13, 2019 16:18
-
-
Save erikfig/c64267d3e4d90322c5905afba3b96091 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class CifraDeCesar | |
{ | |
const IN = 0; | |
const OUT = 1; | |
private $interval; | |
public function __construct($interval) | |
{ | |
$this->setInterval($interval); | |
} | |
public function encode($term) | |
{ | |
$term_iterable = str_split($term); | |
$result = []; | |
foreach ($term_iterable as $letter) { | |
$result[] = $this->translate($letter, self::IN); | |
} | |
return implode('', $result); | |
} | |
public function decode($term) | |
{ | |
$term_iterable = str_split($term); | |
$result = []; | |
foreach ($term_iterable as $letter) { | |
$result[] = $this->translate($letter, self::OUT); | |
} | |
return implode('', $result); | |
} | |
private function setInterval($interval) | |
{ | |
if ($interval < 1) { | |
throw new \Exception("Interval must be bigger of 1"); | |
} | |
$this->interval = $interval; | |
} | |
private function translate($letter, $mode) | |
{ | |
$alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | |
$pos = strpos($alphabet, $letter); | |
if ($pos === false) { | |
return $letter; | |
} | |
if ($mode === 0) { | |
$pos += $this->interval; | |
} | |
if ($mode === 1) { | |
$pos -= $this->interval; | |
} | |
return $alphabet[$pos]; | |
} | |
} | |
$term = 'Erik Figueiredo'; | |
$cifraDeCesar = new CifraDeCesar(3); | |
$encoded = $cifraDeCesar->encode($term); | |
echo $encoded; | |
echo PHP_EOL; | |
echo $cifraDeCesar->decode($encoded); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment