Skip to content

Instantly share code, notes, and snippets.

@imanalopher
Last active June 24, 2016 18:16
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 imanalopher/f7296d5469d2d56b78b11071f7c6c4f5 to your computer and use it in GitHub Desktop.
Save imanalopher/f7296d5469d2d56b78b11071f7c6c4f5 to your computer and use it in GitHub Desktop.
Шифр цезаря
<?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, '');
}
}
@imanalopher
Copy link
Author

imanalopher commented Jun 15, 2016

$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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment