塞萨尔密码的PHP替代编码算法
问题描述:
您好,我在练习中将此练习作为测试的一部分,我该如何解决它或提示要解决它
hello i am stack with this exercise as part of a test, how can i solve it or hint to solve it
/**
* Class SubstitutionEncodingAlgorithm
*/
class SubstitutionEncodingAlgorithm implements EncodingAlgorithm {
/**
* @var array
*/
private $substitutions;
/**
* SubstitutionEncodingAlgorithm constructor.
* @param $substitutions
*/
public function __construct(array $substitutions) {
$this->substitutions = array();
}
/**
* Encodes text by substituting character with another one provided in the pair.
* For example pair "ab" defines all "a" chars will be replaced with "b" and all "b" chars will be replaced with "a"
* Examples:
* substitutions = ["ab"], input = "aabbcc", output = "bbaacc"
* substitutions = ["ab", "cd"], input = "adam", output = "bcbm"
*
* @param string $text
* @return string
*/
public function encode($text) {
/**
* @todo: Implement it
*/
}
}
到目前为止,我已尝试在encode()函数中进行了哪些操作,但仍无法正常工作,这是我做错了什么?
that what i ve tried so far in the encode () function but its not working, what i am doing wrong ?
public function encode($text) {
$length = strlen($text);
$newstr = '';
for ($i = 0; $i < $length; $i++) {
if (is_array($this->substitutions) && in_array(strtoupper($text[$i]), array_flip($this->substitutions)))
$newstr .= $this->substitutions[strtoupper($text[$i])];
}
return $newstr;
}
我知道这是迄今为止要实施的cesar算法,对您有帮助
i understand that it is the cesar algorithm to be implemented so far, any help would be appreciated on how to do it
答
$swapA = array();
$swapB = array();
$output = '';
$aText = str_split($text);
foreach($this->substitutions as $sub)
{
$swapA[] = substr($sub,0,1);
$swapB[] = substr($sub,1,1);
}
foreach ($aText as $letter) {
if (in_array(strtolower($letter, $swapA)) {
$positionOccurence = array_search ($letter, $swapA);
$replaced = $swapB[$positionOccurence];
$output .= str_replace($letter, $replaced, $letter);
} elseif (in_array(strtolower($letter), $swapB)) {
$positionOccurence = array_search ($letter, $swapB);
$replaced = $swapA[$positionOccurence];
$output .= str_replace($letter, $replaced, $letter);
} else {
$output .= $letter;
}
}
return $output;