csansoon

P7.07 X20419 Average length and most frequent letter

Nov 14th, 2018
416
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. const int LENGTH_ALPHABET = 'z' - 'a' + 1;
  7.  
  8. char lletra_mes_frequent(const string& s) {
  9.         vector <int> lmf(LENGTH_ALPHABET, 0);
  10.         int tams = s.size();
  11.         for (int i = 0; i < tams; ++i) {
  12.                 ++lmf[s[i]-'a'];
  13.         }
  14.         int pos, freq = 0;
  15.         for (int i = 0; i < LENGTH_ALPHABET; ++i) {
  16.                 if (lmf[i] > freq) {
  17.                         pos = i;
  18.                         freq = lmf[i];
  19.                 }
  20.         }
  21.         char c = 'a' + pos;
  22.         return c;
  23. }
  24.  
  25.  
  26. //Pre: Llegeix un seguit d'n paraules
  27. //Post: Escriu la longitut mitjana i de totes les paraules que tenen una longitut superior a aquesta, la lletra mĂŠs repetida
  28. int main() {
  29.         cout.setf(ios::fixed);
  30.         cout.precision(2);
  31.         int n;
  32.         double longitut = 0;
  33.         string s;
  34.         cin >> n;
  35.         int aux = n;
  36.         vector<string> v(n); //Guardem la paraula
  37.         vector<int> u(n); //Guardem el tamany de la paraula
  38.         for (int i = 0; i < n; ++i) {
  39.                 cin >> s;
  40.                 int tams = s.size();
  41.                 v[i] = s;
  42.                 u[i] = tams;
  43.                 longitut += tams;
  44.         }
  45.         longitut /= aux;
  46.         cout << longitut << endl;
  47.         for (int i = 0; i < aux; ++i) {
  48.                 if (u[i] >= longitut) {
  49.                         cout << v[i] << ": " << lletra_mes_frequent(v[i]) << endl;
  50.                 }
  51.         }
  52. }
  53.  
  54. // (c) Carlos Sansón (Best pro1 delegate ever for sure) @csansoon
Advertisement
Add Comment
Please, Sign In to add comment