For this problem, the problem seems to be parsing, because the inputs can have newlines inserted randomly between them. so what i did was to just keep parsing out numbers from the input regardless if the number comes after a space or a newline. just keep parsing numbers.

for every number parsed, check the status of the program. a status of 0 means that it is the program start, and so the number just parsed corresponds to the number of cases to be processed. if the status is 1, it means that we already know the number of cases. therefore the number just parsed corresponds to the number of students in a particular test case. a status of 2 means that we are currently extracting the grades of the students in a particular case. a status of 3 means that all cases have been processed and that the program should exit.

if in status 2, the number of student grades extracted becomes equal to the number of students in a particular test case, then we get the average grade of all students in the test case. then we count the number of students whose grade is above the average. then we divide the number of students with above average grade by the total number of students in the particular test case.

#include "stdio.h"

#include "string.h"

#include "stdlib.h"

int main() {

char line[10000];

char *pch;

int num_cases, num_students;

int students_processed, cases_processed;

int grades[10000];

int x, i, num_above;

float ave;

float above_percentage;

// 0 start

// 1 obtained num_cases

// 2 obtained num_students

// 3 all cases processed

int status = 0;

cases_processed = 0;

while (1) {

gets(line);

pch = strtok(line, " \t\n");

while (pch) {

x = atoi(pch);

if (status == 0) {

num_cases = x;

status += 1;

}

else if (status == 1) {

num_students = x;

students_processed = 0;

status += 1;

}

else if (status == 2) {

grades[students_processed] = x;

students_processed += 1;

if(students_processed == num_students) {

cases_processed += 1;

ave = 0;

for (i = 0; i < num_students; i += 1) {

ave += grades[i];

}

ave /= num_students;

for (i = 0, num_above = 0; i < num_students; i += 1) {

if (float(grades[i]) > ave) {

num_above += 1;

}

}

above_percentage = float(num_above) / float(num_students) * 100;

printf("%.3f%\n", above_percentage);

if (cases_processed == num_cases) {

status = 3;

break;

}

status = 1;

}

}

pch = strtok(NULL, " \t\n");

}

if (status == 3) {

break;

}

}

return 0;

}

## No comments:

## Post a Comment