Count the number of words having sum of ASCII values less than and greater than k in C++

C++Server Side ProgrammingProgramming

We are given a string str with a sentence and a number k. The goal is to find the count of in str that have ascii value less than k and words with ascii value greater than k.

ASCII − Unique code as the number assigned to each character in a language.

Let us understand with examples.

Input − str= “This is ASCII”. k=300

Output − Count of the number of words having sum of ASCII values less than k are − 1

Count of number of words having sum of ASCII values greater than k are − 2

Explanation − word “is” has ascii less than 300 other two more.

Input − str= “set set set”. k=300

Output − Count of number of words having sum of ASCII values less than k are − 0

Count of the number of words having sum of ASCII values greater than k are − 3

Explanation − All words are the same and have ascii more than 300.

The approach used in the below program is as follows

We will traverse the string str using a for loop. For each word after space, start adding str[i] to total. If this is >k. Increment count.

  • Take string as str and integer as k.

  • Function words_less_greater(string str, int k, int length) takes string and returns count of words with ascii less and greater than k.

  • Take temp as 0 for ascii of each word in str.

  • Take count as 0 for a count of words with ASCII less than k.

  • Take total as 0 for total words in k.

  • Traverse str using for loop.

  • For each word after a space str[i]==‘ ‘. Add it’s characters str[i] to temp. After the end of word, check if temp<k. If yes increment count and total.

  • If not increment total only.

  • At the end, the count has a number of words having ASCII less than k. total - count will be words with ascii more than k.

  • Print results.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void words_less_greater(string str, int k, int length){
   int temp = 0;
   int total = 0;
   int count = 0;
   for (int i = 0; i < length; ++i){
      if (str[i] == ' '){
         if (temp < k){
            count++;
         }
         temp = 0;
         total++;
      }
      else{
         temp += str[i];
      }
   }
   total++;
   if (temp < k){
      count++;
   }
   cout<<"Count of number of words having sum of ASCII values less than k are: "<< count;
   cout<<"\nCount of number of words having sum of ASCII values greater than k are: "<< total -
   count;
}
int main(){
   string str = "tutorials point";
   int k = 900;
   int length = str.length();
   words_less_greater(str, k, length);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of number of words having sum of ASCII values less than k are: 1
Count of number of words having sum of ASCII values greater than k are: 1
raja
Published on 01-Dec-2020 16:57:19
Advertisements