Reputation: 124
I have to develop an algorithm that will get multiple strings and find the matched substrings across all those strings. and put percentage to that matched text.
For example
this is first string - 100%
this is second string - 76%
Upvotes: 0
Views: 107
Reputation: 6693
Another method would be to work out the differences using php's inbuilt functions then subtract the difference from the count and calculate percentage.
You could put it into one line but for readability, I broke it down into variables.
Note: This requires PHP 7.4^ to execute. Replace the short hand function fn()
with function($x) use ($words) { return in_array($x, $words); }
if your PHP version does not meet the requirement.
function percentageSubStrings(array $inputs, array $needles): array
{
$outputs = [];
foreach($inputs as $input)
{
$words = explode(' ', $input);
$difference = array_diff($words, array_filter($needles, fn($x) => in_array($x, $words)));
$outputs[$input] = ((count($words) - count($difference)) / count($needles)) * 100;
}
return $outputs;
}
See it working over at 3v4l.org where it is compact.
Upvotes: 1
Reputation: 77045
A raw PHP solution is
function getStringPercentages(inputs, needles) {
$outputs = [];
foreach ($inputs as $input) {
$count = 0;
foreach ($needles as $needle) {
if (strpos($input, $needle) !== false) $count++;
}
$outputs[$input] = ($count / count($outputs)) * 100;
}
}
and then you will need to display the raw percentages nicely.
Upvotes: 1