Imprime cada palabra en una oración con su correspondiente promedio de valores ASCII

Dada una oración, la tarea es encontrar el promedio de los valores ASCII de cada palabra en la oración e imprimirlo con la palabra.
Ejemplos: 
 

Input: sentence = "Learning a string algorithm"
Output: 
Learning - 102
a - 97
string - 110
algorithm - 107

Acercarse:
 

  1. Tome una string vacía y comience a recorrer la oración letra por letra.
  2. Agregue una letra a la string y agregue su valor ASCII a la suma.
  3. Si hay un espacio vacío, calcule el promedio dividiendo la suma por la longitud de la string (palabra)
  4. Borre la string para que pueda usarse para la siguiente palabra
  5. También establezca la suma en cero.

A continuación se muestra la implementación del enfoque anterior:
 

C++

// C++ program of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the
// average of each word in a sentence
void calculateAverage(string sentence)
{
    // Word initialised to an empty string
    string word = "";
 
    // Sum of ascii values
    int sum = 0;
 
    int len = sentence.length();
 
    for (int i = 0; i < len; ++i) {
 
        // If character is a space
        if (sentence[i] == ' ') {
 
            // Calculate the average
            int average = sum / word.length();
 
            cout << word << " - "
                 << average << endl;
 
            // Clear the word and
            // set the sum to 0
            word.clear();
            sum = 0;
        }
 
        else {
 
            // Add the ascii value to sum and
            // also add the letter to the word
            sum += sentence[i];
            word += sentence[i];
        }
    }
 
    // Calculate the average of last word
    int average = sum / word.length();
 
    cout << word << " - " << average;
}
 
// Driver code
int main()
{
 
    // Get the sentence
    string sentence
            = "Learning a string algorithm";
 
    // Calculate the average
    calculateAverage(sentence);
 
    return 0;
}

Java

// Java program of the above approach
import java.util.*;
public class Solution
{
// Function to calculate the
// average of each word in a sentence
static void calculateAverage(String sentence)
{
    // Word initialised to an empty string
    String word = "";
 
    // Sum of ascii values
    int sum = 0;
 
    int len = sentence.length();
 
    for (int i = 0; i < len; ++i) {
 
        // If character is a space
        if (sentence.charAt(i) == ' ') {
 
            // Calculate the average
            int average = sum / word.length();
 
            System.out.println( word + " - "+ average );
 
            // Clear the word and
            // set the sum to 0
            word="";
            sum = 0;
        }
 
        else {
 
            // Add the ascii value to sum and
            // also add the letter to the word
            sum += sentence.charAt(i);
            word += sentence.charAt(i);
        }
    }
 
    // Calculate the average of last word
    int average = sum / word.length();
 
System.out.print( word + " - " + average);
}
 
// Driver code
public static void main(String[] args)
{
 
    // Get the sentence
    String sentence
            = "Learning a string algorithm";
 
    // Calculate the average
    calculateAverage(sentence);
 
}
}
//contributed by Arnab Kundu

Python 3

# Python 3 program of the above approach
 
# Function to calculate the
# average of each word in a sentence
def calculateAverage(sentence):
 
    # Word initialised to
    # an empty string
    word = ""
 
    # Sum of ascii values
    sum = 0
 
    l = len(sentence)
 
    for i in range(l):
 
        # If character is a space
        if (sentence[i] == ' ') :
 
            # Calculate the average
            average = sum // len(word)
 
            print(word , " - ", average)
 
            # Clear the word and
            # set the sum to 0
            word = ""
            sum = 0
 
        else :
 
            # Add the ascii value to sum and
            # also add the letter to the word
            sum += ord(sentence[i])
            word += sentence[i]
 
    # Calculate the average of last word
    average = sum // len(word)
 
    print(word , " - " , average)
 
# Driver code
if __name__ == "__main__":
 
    # Get the sentence
    sentence = "Learning a string algorithm"
 
    # Calculate the average
    calculateAverage(sentence)
 
# This code is contributed
# by ChitraNayal

C#

// C# implementation of above approach
using System;
 
class GFG
{
// Function to calculate the
// average of each word in a sentence
static void calculateAverage(String sentence)
{
    // Word initialised to an empty string
    String word = "";
 
    // Sum of ascii values
    int sum = 0;
 
    int len = sentence.Length;
    int average = 0;
    for (int i = 0; i < len; ++i)
    {
         
        // If character is a space
        if (sentence[i] == ' ')
        {
 
            // Calculate the average
            average = sum / word.Length;
 
            Console.WriteLine(word + " - " + average);
 
            // Clear the word and
            // set the sum to 0
            word="";
            sum = 0;
        }
 
        else
        {
 
            // Add the ascii value to sum and
            // also add the letter to the word
            sum += sentence[i];
            word += sentence[i];
        }
    }
 
    // Calculate the average of last word
    average = sum / word.Length;
 
    Console.Write(word + " - " + average);
}
 
// Driver code
public static void Main()
{
    // Get the sentence
    String sentence = "Learning a string algorithm";
 
    // Calculate the average
    calculateAverage(sentence);
}
}
 
// This code is contributed
// by PrinciRaj1992

Javascript

<script>
      // JavaScript implementation of above approach
      // Function to calculate the
      // average of each word in a sentence
      function calculateAverage(sentence) {
        // Word initialised to an empty string
        var word = "";
 
        // Sum of ascii values
        var sum = 0;
 
        var len = sentence.length;
        var average = 0;
        for (var i = 0; i < len; ++i) {
          // If character is a space
          if (sentence[i] === " ") {
            // Calculate the average
            average = parseInt(sum / word.length);
 
            document.write(word + " - " + average + "<br>");
 
            // Clear the word and
            // set the sum to 0
            word = "";
            sum = 0;
          } else {
            // Add the ascii value to sum and
            // also add the letter to the word
 
            sum += sentence[i].charCodeAt(0);
            word += sentence[i];
          }
        }
 
        // Calculate the average of last word
        average = parseInt(sum / word.length);
        document.write(word + " - " + average + "<br>");
      }
 
      // Driver code
      // Get the sentence
      var sentence = "Learning a string algorithm";
 
      // Calculate the average
      calculateAverage(sentence);
    </script>
Producción: 

Learning - 102
a - 97
string - 110
algorithm - 107

 

Complejidad de tiempo : O(N)
 

Publicación traducida automáticamente

Artículo escrito por imdhruvgupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *