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
*/
}
}
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;
}
i understand that it is the cesar algorithm to be implemented so far, any help would be appreciated on how to do it
You could take the substitutions array and split it into two arrays, e.g.
My try - it is just for one byte per char text:
Other solution is much more faster and simpler:
first create in constructor array like:
and then simply make translation: