Skip to content

Instantly share code, notes, and snippets.

@nnnikolay
Created May 22, 2017 09:21
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 nnnikolay/ab98303fd9d520e186231af5831f32ca to your computer and use it in GitHub Desktop.
Save nnnikolay/ab98303fd9d520e186231af5831f32ca to your computer and use it in GitHub Desktop.
Again, from Codility. Need to transform the string regarding the rues as long as there are still matching rules.
<?php
function solution($S)
{
$rules = [
'AB' => 'AA',
'BA' => 'AA',
'CB' => 'CC',
'BC' => 'CC',
'AA' => 'A',
'CC' => 'C',
];
$count = 1;
do {
$matchedRules = array_reduce(array_keys($rules), function($matchedRules, $pattern) use ($S, $rules) {
if (false !== strpos($S, $pattern)) {
$matchedRules[] = [$pattern => $rules[$pattern]];
}
return $matchedRules;
}, []);
if ($matchedRules) {
$ruleIdx = array_rand($matchedRules);
foreach($matchedRules[$ruleIdx] as $search => $replace) {
$S = str_replace($search, $replace, $S, $count);
}
}
} while ($matchedRules);
return $S;
}
echo solution('ABBCC');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment