Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created June 6, 2019 06:27
Show Gist options
  • Select an option

  • Save anushshukla/76b3eff0cf55aa9d8bff31ce1fa89a6f to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/76b3eff0cf55aa9d8bff31ce1fa89a6f to your computer and use it in GitHub Desktop.
Light Build Sequence
<?php
$firstSeqArr = [];
$secondSeqArr = [];
$operations = 0;
while($str = fgets(STDIN)){
$trimmedStr = trim($str);
$trimmedStrSplit = str_split($trimmedStr);
if(empty($firstSeqArr)) {
$firstSeqArr = $trimmedStrSplit;
} else {
$trimmedStrSplit = str_split(substr($trimmedStr, 0, count($firstSeqArr) - 1));
$secondSeqArr = $trimmedStrSplit;
}
}
function isCharArrMatching($matchee, $matcher) {
return implode("", $matchee) === implode("", $matcher);
}
$firstSeqLen = count($firstSeqArr);
$loopLimit = ceil($firstSeqLen/2);
for($index = 0; $index < $loopLimit; $index++) {
$loopLimit = $index - 1;
if(isCharArrMatching($firstSeqArr, $secondSeqArr)) {
break;
}
$backwardIndex = $firstSeqLen - 1 - $index;
$startingChar = $firstSeqArr[$index];
$lastChar = $firstSeqArr[$backwardIndex];
if($startingChar !== @$secondSeqArr[$index]) {
$inserted = array($startingChar);
if(array_key_exists($index, $secondSeqArr) && count($secondSeqArr) === $firstSeqLen) {
$secondSeqArr[$index] = $startingChar;
} else {
array_splice( $secondSeqArr, $index, 0, $inserted );
}
}
if($lastChar !== @$secondSeqArr[$backwardIndex]) {
$inserted = array($lastChar);
if(array_key_exists($backwardIndex, $secondSeqArr)) {
$secondSeqArr[$index] = $lastChar;
} else {
array_splice( $secondSeqArr, $backwardIndex, 0, $inserted );
}
}
$operations++;
}
echo isCharArrMatching($firstSeqArr, $secondSeqArr) ? $operations : NULL;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment