phpstringcountcharacterfind-occurrences

Count the number of times you can make a given word from the letters of a larger text


I wanted to make a function which you can see how many times you can make a given word from a text.

For example:

The text is: Ham followed now ecstatic use speaking exercise may repeated. Himself he evident oh greatly my on inhabit general concern. It allowance prevailed enjoyment in it. Calling observe for who pressed raising his. Can connection instrument astonished unaffected his motionless preference. Announcing say boy precaution unaffected difficulty alteration him.

$text = "Ham followed now ecstatic use speaking exercise may repeated.
Himself he evident oh greatly my on inhabit general concern. It allowance 
prevailed enjoyment in it. Calling observe for who pressed raising his. Can 
connection instrument astonished unaffected his motionless preference. 
Announcing say boy precaution unaffected difficulty alteration him.";

$word = "Potato";

I want to know how many times you can write the word "potato". The expected count is 6 times.

I started with something like this:

function count($text) {
    for ($i = 0; $i <= strlen($text); $i++) {
        if ($text[$i] == "p") {
            $p = 0;
            $p++;
            echo $p;
        }
    }
}

Solution

  • Firstly, you cannot redeclare a count() function -- it is already declared as a native function in PHP.

    Try this recursive function which contains nested loops:

    function countt($text, $word, $count = 0) {
        $found = '';
        for ($i = 0; $i < strlen($word); $i++) {
            for ($j = 0; $j < strlen($text); $j++) {
                if ($word[$i] === $text[$j]) {
                    $text = substr($text, 0, $j) . substr($text, $j + 1);
                    $found .= $word[$i];
                    if ($found === $word) {
                        $count++;
                        return countt($text, $word, $count);
                    }
                    break;
                }
            }
        }
        return $count;
    }
    
    echo countt($text, 'potato');//6
    

    Explanation: This recursive function finds occurrences of each letter of a word in text and removes it from the text. Once it completes the new word that is identical to the searched one, it calls this function again with new text, that misses those used letters, until there is no more letters left that could complete another word.

    You can play with it here: https://3v4l.org/h43rq