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%
Advertisement
Answer
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.