Skip to content

Instantly share code, notes, and snippets.

@aldiunanto
Created September 22, 2019 13:05
Show Gist options
  • Save aldiunanto/ef777388a80ac445de0e3c294c0e4feb to your computer and use it in GitHub Desktop.
Save aldiunanto/ef777388a80ac445de0e3c294c0e4feb to your computer and use it in GitHub Desktop.
Get combination from given array and string
<?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