Skip to content

Instantly share code, notes, and snippets.

@erikfig
Created July 13, 2019 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikfig/c64267d3e4d90322c5905afba3b96091 to your computer and use it in GitHub Desktop.
Save erikfig/c64267d3e4d90322c5905afba3b96091 to your computer and use it in GitHub Desktop.
<?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