Practising Algorithms

When I’m not working with my school- or personal projects I like to do small algorithm challenges. Even if some of these challenges are stuff you rarely will use as a web developer, they will still help you with problem solving and thinking algorithmic.
Two sites I frequently visit are Coderbyte and Codewars, they both offer challenges with varying difficulty.

I thought I would go over a a challenge here with you guys just to show how they might look like and how I would solve it. For this challenge I chose to use JavaScript.

Challenge – Longest Word

Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string.
If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.

For this challenge you are given a function that takes one parameter sen that will be type of string. The challenge is to implement this function to return the longest word in the given string, and if there are two or more words that are the same length, return the first word.

function LongestWord(sen) { 
        return sen; // Implement me

First I would split the string by space, giving me an array of strings.
I would then use a regex pattern to match any word character.
After that I can go by the assumption that the first index of the array will be the longest word, so I store that in a variable named longest.

(Sidenote: when I’m doing more complex patterns I like to use a website called regex101.)

I loop over the array, starting at index of 1 since I’ve already stored index 0 in the variable above. I need to compare all the string’s lengths within the array to the length of longest.
If any string is greater than longest, replace longest with the new value.
Finally return longest, which will now be the longest word in the given sentence.


function LongestWord(sen) { 
    const arr = sen.split(" ");                         // Split into an array
    const regex = /[\w-]+/;                             // Regex pattern to match word characters
    let longest = arr[0].match(regex).toString();       // Index 0 is longest
    for (let i = 1; i < arr.length; i++) {              // Loop from index 1
         let second = arr[i].match(regex).toString();   // Get next match 
         if(longest.length < second.length){            // Compare to longest
             longest = arr[i];                          // If longer, store the new value in longest.
    return longest;                                     // Return the longest word.           
Running the code at CoderByte