Problem 66 my code doesnt decipher all sentences dont know whats wrong

Back to Problem Solutions forum

Photon     2016-04-16 16:55:13
User avatar

Here's my code it fails at some test cases like :

JK OKKJAN OLKGAJ PDWJ XNKGAJ WO AWOU WO HUEJC LKAPNU EO SDWP CAP HKOP EJ PNWJOHWPEKJ

Please, help me track the problem :)

#include <iostream>
#include <cmath>

using namespace std;

char decode (int k, char c);

int main()
{
int n;
cin>>n;
string s;
getline(cin,s);

// average letter frequencies in English
double english[26]={8.167, 1.492, 2.782, 4.253, 12.702, 2.228, 2.015, 6.094, 6.966, 0.153, 0.772, 4.025, 2.406,
   6.749, 7.507, 1.929, 0.095, 5.987, 6.327, 9.056, 2.758, 0.978, 2.361, 0.150, 1.974, 0.074};


for(int i=0;i<n;i++)
{
    getline(cin,s);

    double enc[26]={0.0};
     double dif[26]={0.0};
     double ch[26]={0.0};
    int c=0;
    int spaces = 0;
    for(int j=0; j<26;j++)
    {
        c=0;
        spaces=0;

        for(int z=0; z<s.size(); z++)
        {
            if(s[z]==('A'+j))
            c++;

            if(s[z]==' ')
            spaces++;
        }
        double d = s.size()-spaces;
        enc[j] = c/d*100.0;
        }

for(int x=0;x<26;x++)
     {
       for(int j=0;j<26;j++)
       {
            dif[j] = english[j] - enc[j];
       }

   double sum = 0.0;
    for(int z=0; z<26;z++)
    {
        double val = pow(dif[z],2);
        dif[z]= val;
        sum+= val;
    }
    ch[x] = pow(sum/26.0,2);
   // cout<<" Step: "<<x+1<<" value: "<<ch[x]<<" ";
   // cout<<ch[x]<<" ";

    //rotate array
    double temp = enc[0];
    for(int j=0;j<25;j++)
       {
            enc[j]=enc[j+1];
       }
       enc[25]=enc[0];
    // after rotation
   }

 int min_i = 0;
for(int j=0;j<26;j++)
{
    if(ch[j] < ch[min_i])
    min_i=j;
}

    int sp = 3;
    int iter = 0;
    while(sp)
    {
        cout<<decode(min_i,s[iter]);
        if(s[iter]==' ')
        sp--;
        iter++;
    }
            cout<<min_i<<" ";

}
return 0;
}


char decode (int k, char c)
{
if(c=='.'|| c==' ')
return c;

if(c-k < 'A')
{
    return c+26-k;
}
else
return c-k;
}
Quandray     2016-04-24 14:32:18
User avatar

I see that you've managed to solve it

Please login and solve 5 problems to be able to post at forum