Wednesday, May 22, 2013

File compare

Today's problem must be solved in C++ without any special libraries (namely boost). There's an unknown number of  files of the format:

File1_1.txt // the files all start with File, followed by some number < 9999
followed by _1.txt
There's 5 lines of comments about this file.
These comments can contain any characters
such as `~!@#$%^&*()_+-=[]{};':",./<>? and not be disrupted
156 1.569e-1
200 0.5e+09
215 569
289 159E+009
350 150

For each of these files, there's a file with the exact same name in a folder in the parent directory of the current working directory. That file with the same name looks exactly the same, except for when we get to the numbers. Specifically the second number is different, i.e. :
156 1.568e-1
200 0.5e+09
215 569
289 159E+009
350 159

Within two same name files we will need to calculate the difference of the second number and find the largest difference in this file. Because 150 - 159 gives us abs(-9) == 9, 9 is the biggest difference for this particular file. We will not need to compare different lines.

The goal is to find the largest difference (absolute value of the difference) among all the files.

1 comment:

  1. Here's my solution, given in C++, I left out the includes because it's space wasting. let me know if you want them.

    using namespace std;

    template
    T StringToNumber ( const string &Text, T defValue = T() )
    {
    stringstream ss;
    for ( string::const_iterator i=Text.begin(); i!=Text.end(); ++i )
    if ( isdigit(*i) || *i=='e' || *i=='-' || *i=='+' || *i=='.' )
    ss << *i;
    T result;
    ss >> result ? result : defValue;
    return result ? result : defValue;
    }

    int main () {
    string line;
    float a, b;
    float largest = 0;

    for(int i = 1; i < 10; i++){

    stringstream file1;
    stringstream file2;
    file1 << "file" << i << "_1.txt";
    file2 << "file" << i << "_2.txt";
    ifstream myfile1(file1.str().c_str());
    ifstream myfile2(file2.str().c_str());

    //StringToNumber("145.654e+03", 0.0);
    //cout << atof("1.256E+01") << endl;
    if (myfile1.is_open() && myfile2.is_open()){

    for(int i = 0; i < 5; i++){
    getline(myfile1, line);
    getline(myfile2, line);
    }

    while (myfile1.good() && myfile2.good()){
    myfile1 >> line;
    myfile2 >> line;

    myfile1 >> line;
    a = StringToNumber(line, 0.0);
    myfile2 >> line;
    b = StringToNumber(line, 0.0);
    float absVal = a - b;
    if(abs(a - b) > largest)
    largest = abs(a - b);
    }
    myfile1.close();
    }
    }
    cout << "largest = " << largest << endl;
    system("pause");
    return 0;
    }

    ReplyDelete