Inherited Code in C++ – Hacker Rank Solution

Inherited Code in C++ - Hacker Rank Solution
Inherited Code in C++ – Hacker Rank Solution

Problem

You inherited a piece of code that performs username validation for your company’s website. The existing function works reasonably well, but it throws an exception when the username is too short. Upon review, you realize that nobody ever defined the exception.

The inherited code is provided for you in the locked section of your editor. Complete the code so that, when an exception is thrown, it prints Too short: n (where n is the length of the given username).


Input Format :

The first line contains an integer, t, the number of test cases.
Each of the t subsequent lines describes a test case as a single username string, n.

Constraints :

  • 1 <= t <= 1000
  • 1<= |u| <= 100
  • The username consists only of uppercase and lowercase letters.

Output Format :

You are not responsible for directly printing anything to stdout. If your code is correct, the locked stub code in your editor will print either Valid (if the username is valid), Invalid (if the username is invalid), or Too short: n (where n is the length of the too-short username) on a new line for each test case.


Sample Input :

3
Peter
Me
Arxwwz

Sample Output :

Valid
Too short: 2
Invalid

Explanation :

Username Me is too short because it only contains 2 characters, so your exception prints Too Short : 2.
All other validation is handled by the locked code in your editor.



Inherited Code in C++ – Hacker Rank Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
// Write your Student class here
class Student
{
    private:
    int scores[5];
    public:
    void input()
    {
        for (int i = 0; i < 5; i++)
        {
            cin >> scores[i];
        }
    }
    int calculateTotalScore()
    {
        int count = 0;
        for (int i = 0; i < 5; i++)
        {
            count += scores[i];
        }
        return count;
    }
};
int main()
{
    int n; // number of students
    cin >> n;
    Student *s = new Student[n]; // an array of n students
    for(int i = 0; i < n; i++)
    {
        s[i].input();
    }
    // calculate kristen's score
    int kristen_score = s[0].calculateTotalScore();
    // 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;
}

Disclaimer: The above Problem (Inherited Code in C++ ) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment