Hear this problem: Write a C/C++ program that reads all the values from the "BAC.TXT" file and determines which are the two largest three digit numbers that are missing from the file using a time-efficient algorithm. This is the code that I wrote and it returned good values for all the input sets I tried:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ ifstream in("BAC.TXT");
unsigned int a[1000], missing_numbers[2];
unsigned int data, i = 0, j = 0, found_missing_numbers = 0;
while(!in.eof())
{ in >> data;
if (data >= 100 && data <= 999)
a[data] = 1;
}
for(i=999;i>=100;i--)
{if(a[i]!=1)
{ missing_numbers[j] = i;
found_missing_numbers++;
j++;
}
if (found_missing_numbers == 2)
break;
}
if (found_missing_numbers == 2)
{
cout << "The two largest numbers of three digits that are missing from the file are:";
cout << missing_numbers[0] << " and " << missing_numbers[1];
}
else if (found_missing_numbers == 1)
cout << "Only one three digit number is missing from the file:" << missing_numbers[0];
else
cout << "There are no three digit numbers missing from the file.";
cin.get();
in.close();
return 0;
}
Example of Input:
125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 1112 125 997 12315 122 54 9 5546 754 998 12312 12152 745 2354 856 124 956 125 88556 2534 12 456668 12 56324 4521 3 652 999 94 24521 6524 11
Output:
The two largest numbers of three digits that are missing from the file are:996 and 995
I consider the code quite efficient because the file is read a single time and it selects and works only with the data that could help to find the solution. I would like to hear your opinion, other suggestions, all that you consider that could make this solution more efficient.
P.S. I am a beginner in programming, don't know any OOP for the moment. I know the code I wrote is something like C with cout
and cin
...not C++. Don't kill me. This question is based on the same problem that I was solving here, but now I have a working solution. Now it's only a matter of optimisation.