C++ code for Finding ranks in a vector array
I just made this function, which to be honest, I have been tinkering with since 3 days, it is a part of a problem statement in a hackerRank problem. At the beginning there were a lot of grey areas in my approach for this problem but today I thought about a completely different approach, which as I had expected worked completely fine, after going through a tortous journey full of errors, I am not exaggerating but, the compiler of programiz is sometimes very grievous, in the beginning it was not accepting vector header file, but it did accept after refreshing the page. I will be using this function for solving the Climbing the leaderboard problem of HackerRank.
#include <iostream>
#include<vector>
using namespace std;
void display(vector<int> array){
for(int i=0;i<array.size();i++){
cout<<array[i]<<" ";
}
}
vector<int> rankGiver(vector<int> arr){
int temp;
vector<int> array(arr);
for(int i=0;i<arr.size()-1;i++){
for(int j=0;j<arr.size()-1-i;j++){
if(arr[j]>arr[j+1]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<"\nThe array passed to the function rankGiver after sorting process\n";
display(arr);
vector<int> rank(arr.size());
rank[arr.size()-1]=1;
for(int i=arr.size()-2;i>=0;i--){
if(arr[i]==arr[i+1]){
rank[i]=rank[i+1];
}else{
rank[i]=rank[i+1]+1;
}
}
cout<<endl;
cout<<"The rank array inside the function rankGiver\n";
display(rank);
int count=0;
for(int k=0;k<array.size();k++){
for(int l=k+1;l<array.size();l++){
if(array[k]==arr[l]){
array[k]=rank[l];
}
}
}
cout<<"\nThe final returned array by the function\n";
return array;
}
int main() {
// Write C++ code here
// std::cout << "Hello world!";
vector<int> arr{
12,23,4,5,67,4
};
display(arr);
vector<int> vect;
vect=rankGiver(arr);
cout<<"\n";
display(vect);
return 0;
}
Comments
Post a Comment