C++ code to find position of students after coding contest

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have an array A with n elements. In a coding contest, in total n students will participate, and before the start, every one of them has some positive rating (integer). A[i] represents the rating of ith student. After the contest ends, every student will end up with some positive integer position. We are expecting the students will take places according to their ratings. If student A has rating strictly lower than student B, A will get strictly greater position than B. We have to find the position at the end of the contest.

So, if the input is like A = [3, 5, 3, 4, 5], then the output will be [4, 1, 4, 3, 1] because 2nd and 5th students share the first position with highest rating, 4th student is next with third position, 1st and 3rd students are the last sharing fourth position.

Steps

To solve this, we will follow these steps −

n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
d := 1
for initialize j := 0, when j < n, update (increase j by 1), do:
if A[j] > A[i], then:
(increase d by 1)
cout << d << ", "

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A){
int n = A.size();
for (int i = 0; i < n; i++){
int d = 1;
for (int j = 0; j < n; j++){
if (A[j] > A[i])
d++;
}
cout << d << ", ";
}
}
int main(){
vector<int> A = { 3, 5, 3, 4, 5 };
solve(A);
}

Input

{ 3, 5, 3, 4, 5 }

Output

4, 1, 4, 3, 1,
Updated on 15-Mar-2022 06:58:57