/***************************************************************
Here's a good problem to work on, as it takes into account a
number of the things we've talked about:  The file scores.txt
contains the scores of students on various problems on an exam.  
Each row corresponds to a student, and the scores along that 
row are that student's scores on problems 1, 2, 3 etc.

Your job: figure out which problem was the hardest!  You may
assume that for every problem, at least one student got full
credit for that problem.  If the average score for problem X as
a percentage of the full credit score for X is less than the 
average score for problem Y as a percentage of the full credit
score for Y, then problem X is "harder" than problem Y.
***************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

double** readGrades(int& ns, int& np);
double* getAveragePercentage(double** P, int ns, int np);
int indexOfMin(double* A, int np);

int main()
{
  int ns, np;
  double** P = readGrades(ns,np);  
  double* A = getAveragePercentage(P,ns,np);
  int imin = indexOfMin(A,np);
  cout << "Problem p" << imin+1 << " is hardest (ave = " << A[imin] << "%)" << endl;    
  return 0;
}

double** readGrades(int& ns, int& np)
{
  // Get size and allocate 2D array
  ifstream fin("scores.txt");
  string junk;
  fin >> ns >> junk >> np >> junk;
  double** P = new double*[ns];
  for(int i = 0; i < ns; i++)
    P[i] = new double[np];

  // Read values into 2D array
  for(int j = 0; j < np; j++) // read problem numbers
    fin >> junk;
  for(int i = 0; i < ns; i++)
    for(int j = 0; j < np; j++)
      fin >> P[i][j];

  return P;
}

double max(double a, double b) { return a < b ? b : a; }

double* getAveragePercentage(double** P, int ns, int np)
{
  double* A = new double[np];
  for(int j = 0; j < np; j++)
  {
    // find maximum score in column j
    double maxScore = P[0][j];
    for(int i = 1; i < ns; i++)
      maxScore = max(maxScore,P[i][j]);

    // find average of scores in column j (as a precentage of the top score)
    double sum = 0;
    for(int i = 0; i < ns; i++)
      sum += P[i][j]/maxScore * 100.0;
    
    A[j] = sum/ns;
  }
  return A;
}

int indexOfMin(double* A, int np)
{
  int imin = 0;
  for(int i = 2; i < np; i++)
    if (A[imin] > A[i])
      imin = i;
  return imin;
}