Classes and Objects

I received an email inviting me to solve the Classes and Objects challenge at HackerRank. If interested please take a look at the requirements and give it a try before reading my solution.

The requirements call for the design of a class with two methods. One of them reads grades from standard input while the other computes the total score for a set of five grades.

Following is a screen capture of the console generated using the provided sample input:

3
30 40 45 10 10
40 40 40 10 10
50 20 30 10 10
1

Seems that there is a student (grades for Kristen are on the first row) that has better scores.

Following is my solution implemented using C++ using Visual Studio 2017 Enterprise Edition:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>

using namespace std;

class Student {

	// **** ****

public:
	int grades[5];

	/*
	*/
	void input() {
		for (int i = 0; i < 5; i++) {
			cin >> grades[i];
		}
	}

	/*
	*/
	int calculateTotalScore() {
		int total = 0;
		for (int i = 0; i < 5; i++) {
			total += grades[i];
		}
		return total;
	}
};

int main() {

	int n;			// number of students
	cin >> n;

	// **** create array of students ****

	Student *s = new Student[n]; // an array of n students

	// **** populate grades ****

	for (int i = 0; i < n; i++) {
		s[i].input();
	}

	// **** calculate kristen's score ****

	int kristen_score = s[0].calculateTotalScore();
	//cout << "main <<< kristen_score: " << kristen_score << endl;

	// **** determine how many students scored higher than kristen ****

	int count = 0;
	for (int i = 1; i < n; i++) {
		int total = s[i].calculateTotalScore();
		if (total > kristen_score) {
			count++;
		}
	}

	// **** print result ****

	cout << count;

	// **** ****

	return 0;
}

This code passed the 11 test cases.

If you have comments or questions regarding this post please leave them in the space provided after the post. I will respond as soon as possible.

Enjoy;

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.