Created
September 22, 2019 13:05
-
-
Save aldiunanto/ef777388a80ac445de0e3c294c0e4feb to your computer and use it in GitHub Desktop.
Get combination from given array and string
This file contains 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 getStringCombination($word, $dict) | |
{ | |
$result = []; | |
if (empty($word)) { | |
return $result; | |
} | |
foreach ($dict as $index => $str) { | |
if (strpos($word, $str) === 0) { | |
$substr = substr($word, strlen($str)); | |
$clonedDict = $dict; | |
unset($clonedDict[$index]); | |
$subResult = getStringCombination($substr, $clonedDict); | |
if (! empty($subResult)) { | |
foreach ($subResult as $subRes) { | |
$result[] = array_merge([$str], $subRes); | |
} | |
} else { | |
$result[] = [$str]; | |
} | |
} | |
} | |
return $result; | |
} | |
$dictionary = ['pro', 'gram', 'merit', 'program', 'it', 'programmer']; | |
$input = 'programmerit'; | |
print_r(getStringCombination($input, $dictionary)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment