Skip to content
Advertisement

Finding the highest scoring word in a string, based on value of letter?

Given a string of words, I need to find the highest scoring word. Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc. I need to return the highest scoring word as a string.

So in the string 'man i need a taxi up to ubud' the correct return string would be taxi since it has high value letters like t and x.

My confusion lies in how to assign each letter in each word a value. I understand to explode the input string and then foreach over that to explode the words but how to increment the value based on the order in the alphabet? I’m very confused.

function high($x) {
    $alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", 
                "u", "v", "w", "x", "y", "z"];
    $nA = array_flip($alphabet);

    $words = explode(" ", $x);
    foreach($words as $w) {
      explode("", $w);
    }
    return "";
}

Advertisement

Answer

As you don’t actually care about the score, more the word with the highest characters, you can use ord() to work out the ascii value. This has the alphabet in ascending order and so gives a higher value – but it’s still based on position.

This splits the words, then for each word adds the ascii value and keeps a track of the highest…

function high($x) {
    // Split sentence into words (lower cased)
    $words = explode(" ", strtolower($x));
    $max = 0;
    $maxWord = '';
    foreach($words as $w) {
        // Keep track of 'value' of word
        $value = 0;
        // For each letter of the word ($i)...
        for ( $i = 0, $len = strlen($w); $i < $len; $i++ )  {
            // $w[$i]  is the letter we are dealing with (treat a string as an array)
            // Take the ascii value of this character and adjust it by 'a'
            $value += (ord($w[$i]) -ord('a'));
        }
        // Check if the new highest value
        if ( $value > $max )    {
            $max = $value;
            $maxWord = $w;
        }
    }
    return $maxWord;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement