Friday, 1 March 2019

Input: 


2 arrays (one with x co-ordinates and another with y co-ordinates) to describe the points

Objective:


To arrange in ascending order of the x-ordinates and if same then descending order of their y-ordinates

Approach:


Using c++ stl, vector, pair, sort method

(It was asked in amazon 2019 campus recruitment for 20 marks)

Run and check at  here


 #include<bits/stdc++.h>  
 using namespace std;  
 bool sortBylogic(const pair<int,int> &a,  
 const pair<int,int> &b)  
 {  
 if(a.first!=b.first)  
 return(a.first < b.first);  
 else  
 return(a.second > b.second);  
 }  
 int main()  
 {  
 //{4,3},{2,1},{2,6},{3,0} => 2,6 2,1 3,0 4,3  
 vector< pair <int,int> > pts; //both x and y coordinates of the point will be stored here as pairs  
 int inX[]={4,2,2,3};  
 int inY[]={3,1,6,0};  
 for(int i=0;i<4;i++)  
 {  
 pts.push_back(make_pair(inX[i],inY[i]));  
 }  
 sort(pts.begin(),pts.end(),sortBylogic);  
 for (int i=0; i<4; i++)  
 {  
 cout << pts[i].first << " "<< pts[i].second << endl;  
 }  
 }  

No comments:

Post a Comment