Created
May 22, 2017 09:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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