Hi everyone.
I’m trying to figure out some code that will take a string, for example ABCDE
One of the arguments should be the number of recursions.
If the number is 0, then the string should be returned as is (obviously, that’s pretty easy to implement).
However, with one recursion, an array with the following values should be returned.
[ 'ABCDE', ' BCDE', 'A CDE', 'AB DE', 'ABC E', 'ABCD ', ]
I’ve added spaces just to make it clear where the letters are omitted, but they shouldn’t be there in the returned strings.
If the number of recursions is set to 2, then we should get the above array as well as the following:
[ ' CDE', ' B DE', ' BC E', ' BCD ', 'A DE', 'A C E', 'A CD ', 'AB E', 'AB D ', 'ABC ', ]
Essentially, the second set of results can be created with the following loop.
`
$str = ‘ABCDE’;
$strArr = [];
$tmpStr = ‘’;
for ($i = 0; $i < strlen($str); $i++) {
for ($c = 0; $c < strlen($str); $c++) {
if ($i !== $c) {
$tmpStr …= substr($str, $c, 1);
}
$strArr[] = $tmpStr;
}
}
And the third set of results can be created like this:
for ($i = 0; $i < strlen($str); $i++) {
for ($c = 0; $c < strlen($str); $c++) {
for ($j=0; $j < strlen($str); $j++) {
if ($i !== $c && $j !== $c) {
$tmpStr …= substr($str, $c, 1);
}
$strArr[] = $tmpStr;
}
}
}
It goes without saying how to do the forth, fifth and so on. I figured the solution must involve recursion.
I know this question looks a bit ‘homeworky’, but I promise it’s not. This is for a database project I am making for indexing words in a way that will make them easier to search in a specific way. I’d appreciate it if anyone could help here. I’ve made recursive functions before, but this one is driving me crazy. I’ve been working on it for hours and I just can’t get it right.
Many thanks in advance.