06
Jan
2020

Hackerrank Compare the Triplets (C++)

C++ :

vector compareTriplets(vector a, vector b) {
     vector result(2);
     int aPoints = 0;
     int bPoints = 0;
     for(int i = 0; i < a.size(); i++){
        if(a[i] < b[i]){
           bPoints++;
        }else if (a[i] > b[i]){
           aPoints++;
        }
     }
     result[0] = aPoints;
     result[1] = bPoints;

     return result;
}

Explanation:

A bit of hard coding here, not the most elegant solution. But hey it works. The for loop compares each number in both vectors a and b at index i to see if either number is larger. If a[i] is larger than b[i], add a point to aPoints, and if b[i] is larger than a[i], add a point to bPoints. Do nothing if a[i] is equal to b[i]. At the end, assign aPoints to result[0], and bPoints to result[1], and return result.

Flaws of solution: result[index] is hardcoded, so extending this answer is going to be troublesome.

You may also like...

Leave a Reply

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