0

Paradox with averages Programming problem

  • I have an class of Computer Science students represented with an array, and a class of Economics students also represented as an array.

  • The array is filled with values representing each students IQ.

  • One well-known joke goes as follows: If a bad Computer Science student drops out of college and goes to a different college to study Economics instead, he will increase the average intelligence on both colleges.

  • I have to run through the computer science array and check if each student leaves and joins economics, will he increase the average IQ of both groups. I then have to count how many students and print to the screen.

I seem to have gotten the right answer but one of the test cases is wrong, can anyone lay their wisdom upon me? thanks.

int main() {

int cases;
cin >> cases;

for(int i = 0; i < cases; i++)
{
    int numCs;
    int numEc;
    cin >> numCs;
    cin >> numEc;

    int csArray[numCs];
    int ecArray[numEc];
    long csTotal = 0;
    long ecTotal = 0;

    for(int j = 0; j < numCs; j++)
    {
        cin >> csArray[j];
        csTotal += csArray[j];
    }
    for(int j = 0; j < numCs; j++)
    {
        cin >> ecArray[j];
        ecTotal += ecArray[j];
    }

    double csAvg =  csTotal / (double)numCs;
    double ecAvg = ecTotal / (double)numEc;

    int count = 0;
    for(int j = 0; j < numCs; j++)
    {
        if((csArray[j] < csAvg) && (csArray[j] > ecAvg))
        {
            count++;
        }
    }

    cout << count << endl;

}

return 0;

}

Eric
  • 53
  • 9
  • Stuff like `int csArray[numCs];` actually isn't valid in C++, and it won't compile on other compilers. This is because C++ doesn't have variable length arrays, and your code only compiles because of a GCC non-standard extension. You should make the array size constant or use an [`std::vector`](https://en.cppreference.com/w/cpp/container/vector). You should also get a [good book](https://stackoverflow.com/q/388242/9254539), since whoever taught you that clearly isn't a good C++ teacher. – eesiraed Jul 07 '18 at 18:12
  • Hey thanks for the info. Unfortunately this is only my second program in c++, I have only learned java so far and some of the problems have less time limits, so I try to copy my java code into c++ using google mainly. I plan on getting to learn the language properly in the coming weeks. Thanks again. – Eric Jul 08 '18 at 20:32

1 Answers1

0

You second loop should run till numE not numC. Also floating point division can be tricky at times since it is a finite approximation so line

if((csArray[j] < csAvg) && (csArray[j] > ecAvg))

can be replaced by

(csTotal > numCs * csArray[j]) && (ecTotal < numEc * csArray[j])

This conveys the same meaning without the hassle of floating point computation.

random40154443
  • 1,100
  • 1
  • 10
  • 25