DEV Community

dev.to staff
dev.to staff

Posted on

4

Daily Challenge #298 - Find the Shortest Word

Given a string of words, return the length of the shortest word in the string.

Examples

find_short("bitcoin take over the world maybe who knows perhaps"), 3)
find_short("turns out random test cases are easier than writing out basic ones"), 3)

Tests

find_short("let us talk about javascript")
find_short("i want to travel the world writing code one day")
find_short("Lets all go on holiday somewhere very cold")

Good luck!


This challenge comes from A.Partridge on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (8)

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Here is a silly answer in the same spirit as the sorting by using time outs. The idea is, instead of trying to calculate/compare sizes, setting a timeout for each word with a delay equal to its length. The timeout callback will show the result and cancel the other timeouts.

Here is the code (demo with the code running on Codepen):

function find_short(str) {
  let timers = {};

  const removeTimers = () => {
    Object.keys(timers).forEach(el => clearTimeout(timers[el]));
  }

  const setTimer = word => {
    timers[word] = setTimeout(
      function() { 
        alert(`The shortest word has ${word.length} characters`);
        removeTimers();
      }, 
      word.length
    );
  };

  str.split(" ").forEach(word => setTimer(word));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bugb profile image
bugb • Edited

nice, you are so creative!

Collapse
 
lizard profile image
Lizard

Here is an answer in python

def find_short(s: str) -> int:
    """
    Returns the length of the shortest word in the string s
    """
    lengths = map(lambda w: len(w), s.split())
    return min(lengths)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ruudgianesini profile image
Ruud Gianesini

Here is an answer in node (first time I write something in node :) ) :

function find_short(phrase: string) { 
 return phrase.split(' ').reduce( (p, c, i) => (i==0 || c.length < p.length) ? c : p)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peter279k profile image
peter279k

Here is the simple solution with PHP:

function findShort($str) {
  $freqLen = [];
  $strs = explode(' ', $str);
  foreach ($strs as $str) {
    $freqLen[] = strlen($str);
  }

  return min($freqLen);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aminnairi profile image
Amin

Elm

import String exposing (words, length)
import List exposing (foldl)


shortestLength : String -> Length
shortestLength text =
    text
        |> words
        |> foldl (\a b -> if length a < length b then a else b) text
        |> length
Enter fullscreen mode Exit fullscreen mode
Collapse
 
celyes profile image
Ilyes Chouia • Edited

Here's the solution in PHP

Note: works only on 7.4+

function find_short(string $str): int
{
    $str = explode(' ', $str); // you can use preg_split('/\s/', $str);
    usort($str, fn($a, $b) => strlen($a) > strlen($b));
    return strlen($str[0]);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bugb profile image
bugb • Edited

My js solution:

find_short=s=>Math.min(...s.split` `.map(v=>v.length))|0
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay