Last active
June 24, 2016 18:16
-
-
Save imanalopher/f7296d5469d2d56b78b11071f7c6c4f5 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 CesarCipher | |
{ | |
private $alphabet; | |
private $shift; | |
/** | |
* @param string $alphabet | |
*/ | |
public function setAlphabet($alphabet) | |
{ | |
$this->alphabet = $alphabet; | |
} | |
/** | |
* @param int $shift | |
* | |
* The $shift parameter must be a positive integer | |
*/ | |
public function setShift($shift) | |
{ | |
$this->shift = $shift; | |
} | |
/** | |
* @param string $plainText | |
* @return string | |
*/ | |
public function encode($plainText) | |
{ | |
$encodedText = []; | |
$plainTextLength = strlen($plainText); | |
$alphabetLength = strlen($this->alphabet); | |
for ($index = 0; $index < $plainTextLength; $index++) { | |
$position = strpos($this->alphabet, $plainText[$index]); | |
$encodedText[] = $position !== false ? $this->alphabet[($position + $this->shift)%$alphabetLength] : $plainText[$index]; | |
} | |
return implode($encodedText, ''); | |
} | |
/** | |
* @param $encodedText | |
* @return string | |
*/ | |
public function decode($encodedText) | |
{ | |
$decodedText = []; | |
$plainTextLength = strlen($encodedText); | |
$alphabetLength = strlen($this->alphabet); | |
for ($index = 0; $index < $plainTextLength; $index++) { | |
$position = strpos($this->alphabet, $encodedText[$index]); | |
$n = ($position - $this->shift)%$alphabetLength; | |
$element = $n > 0 ? $this->alphabet[$n] : $this->alphabet[abs(($n + $alphabetLength)%$alphabetLength)]; | |
$decodedText[] = $position !== false ? $element : $encodedText[$index]; | |
} | |
return implode($decodedText, ''); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$n = new CesarCipher();
$n->setAlphabet("abcdefghijklmnopqrstuvwxyz");
$n->setShift(3);
$s = "The quick brown fox jumps over the lazy dog";
echo $s."\n";
$s = $n->encode($s);
echo $s."\n";
echo $n->decode($s);