0

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%

1
  • 1
    That sounds good but you don't really need to let us know what you're planning to do. You can go ahead and do it and let us know what difficulties you've encountered Commented May 12, 2021 at 15:21

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Rather than nested loops and counters, you could utilise a count() on an array_filter() append: count(array_filter($needles, fn($subStr) => strpos($input, $subStr))) / count($needles) * 100. +1 for concept however.
@Jaquarh yes, that's another possible solution. I've chosen this because it contains an algorithm that the asker might understand. However, standard PHP functions will work just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.