how to split a string into n parts(non-empty substring) with all possible ratios | PHP | Javascript
Let suppose, I have a string(programming language can be either PHP or js)
$s = "abcd";
I want to split this string into substrings(non-empty) into 3 parts with all possible combinations. So the output should be
$result = [
["a", "b", "cd"],
["ab", "c", "d"],
["a", "bc", "d"]
]
I tried with for loop, but the value is overlapped and I don't want to repeat the string.
<?php
function solution($s) {
$n = strlen($s);
$result = [];
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
$s1 = substr($s, 0, $j);
$s2 = substr($s, $i, $j);
$s3 = substr($s, $j, $n);
$temp = [$s1, $s2, $s3];
array_push($result, $temp);
}
}
return $result;
}
$s = "abcd";
print_r(solution($s));
?>
If I get the idea about how we can calculate the possible ratio for a single number then I have a solution ready that gives me the desired output.
<?php
$possibleRatios = [
[1, 1, 2],
[2, 1, 1],
[1, 2, 1]
];
$result = [];
for ($i = 0; $i < count($possibleRatios); $i++) {
$element = $possibleRatios[$i];
$s1 = substr($s, 0, $element[0]);
$s2 = substr($s, $element[0], $element[1]);
$s3 = substr($s, $element[0] + $element[1], $element[2]);
$temp = [$s1, $s2, $s3];
array_push($result, $temp);
}
print_r($result);
In my case, the length of the string is 4 so I want the possible ratio 1:1:2, 2:1:1, 1:2:1. I know the other possible ratios can be 0:1:3, 1:0:3 but I actually want to skip the empty substring combination.
Solution 1:
Example in js
const string = "abcd";
const array = string.split("");
const output = array.reduce((carry, _, idx, arr) => {
if (idx < arr.length - 1) {
const str = arr[idx] + arr[idx + 1];
const subArray = [...arr];
subArray.splice(idx, 2, str);
carry.push(subArray);
}
return carry;
}, []);
console.log(output);
Example in php
<?php
$str = "abcd";
$array = str_split($str);
$output = array_reduce($array, function ($carry) use ($array) {
$idx = $carry['idx'];
if ($idx < count($array) - 1) {
$str = $array[$idx] . $array[$idx + 1];
$subArray = $array;
array_splice($subArray, $idx, 2, $str);
$carry['output'][] = $subArray;
}
$carry['idx'] += 1;
return $carry;
}, ['output' => [], 'idx' => 0])['output'];
var_dump($output);