Saturday, May 27, 2023
HomeSoftware EngineeringMethods to Discover the Shortest Phrase in C++

Methods to Discover the Shortest Phrase in C++


The problem

Easy, given a string of phrases, return the size of the shortest phrase(s).

The string won’t ever be empty and you don’t want to account for various information sorts.

The answer in C++

Choice 1:

int find_short(const std::string &str) {
    std::istringstream inp(str);
    std::string s;
    int len = -1;
    whereas (std::getline(inp, s, ' '))
        if (s.size() < len)
            len = s.size();
    return len;
}

Choice 2:

int find_short(std::string str) {
    std::istringstream iss(str);
    std::vector<std::string> vec{ std::istream_iterator<std::string>(iss), {} };
    return std::min_element(vec.start(), vec.finish(), [](const std::string& s1, const std::string& s2) { return s1.size() < s2.size(); })->size();
}

Choice 3:

#embrace <sstream>

int find_short(std::string str) {
  std::stringstream ss(str);
  auto buff = std::string();
  auto shorter = std::numeric_limits<size_t>::max();
  whereas (ss >> buff)
    shorter = min(shorter, buff.dimension());
  return shorter;
}

Take a look at circumstances to validate our answer

Describe(Exams)
{
  It(Sample_Test_Cases)
  {
    Assert::That(find_short("bitcoin take over the world possibly who is aware of maybe"), Equals(3));
    Assert::That(find_short("seems random check circumstances are simpler than writing out primary ones"), Equals(3));
    Assert::That(find_short("lets speak about javascript the very best language"), Equals(3));
    Assert::That(find_short("i wish to journey the world writing code in the future"), Equals(1));
    Assert::That(find_short("Lets all go on vacation someplace very chilly"), Equals(2));
    Assert::That(find_short("Let's journey overseas lets"), Equals(2));
  }
};
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments