塞萨尔密码的PHP替代编码算法 [英] php Substitution Encoding Algorithm using cesar cipher
本文介绍了塞萨尔密码的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;
这篇关于塞萨尔密码的PHP替代编码算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文