-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path04_car_sorting_problem.cpp
124 lines (100 loc) · 2.74 KB
/
04_car_sorting_problem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
TOPIC: Using Vector (with Pair)
Car Sorting Problem
--------------------
We want to book a cab.
Assume that we are standing at origin(0,0).
we are provides 3 inputs: 1 cab name & 2 as coordinates (xi,yj).
So, we have to sort the cab on the basis of distance from our location (i.e (0,0)) &
if distance of two cabs are same, then sort according to the name.
^
| c1
c4 | (x1,y1)
(x4,y4) | c2
| (x2,y2)
<---------------|---------------->
(0,0)|
| c3
| (x3,y3)
|
v
Approach: Using [vector + custom class]
*/
#include<iostream>
#include<vector>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
class Car
{
public:
string car_name;
int x,y;
Car(string name, int x, int y) // parameterized constructor
{
car_name = name;
this->x = x;
this->y = y;
}
int find_dist()
{
// returns square of dist from origin
return x*x + y*y;
/* The 2D distance between two points A(x₁, y₁) & B((x₂, y₂)) is √[(x₂ - x₁)² + (y₂ - y₁)²]
when, (x₁, y₁) = (0,0)
then, Distance : √[(x₂)² + (y₂)²]
*/
}
};
bool compare(Car c1, Car c2)
{
int distance1 = c1.find_dist();
int distance2 = c2.find_dist();
// If two cabs have same distance, then sort according to car name.
if(distance1 == distance2)
{
// return c1.car_name.length() < c2.car_name.length();
return c1.car_name < c2.car_name;
}
return distance1 < distance2;
}
int main()
{
int n;
cout << "Enter total cabs: ";
cin >> n;
vector<Car> v;
cout << "Enter Car [Name & Coordinates(xi,yj)]: ";
for(int i=0; i<n; i++)
{
int x,y;
string name;
cin >> name >> x >> y;
Car obj(name,x,y);
v.push_back(obj);
}
// sort car according to distance
sort(v.begin(),v.end(), compare);
// for each loop
cout << "Car [Sorted Order]: \n";
for(auto i:v)
{
cout << i.car_name << " " << i.x << " " << i.y << " | Distance: " << i.find_dist()<< endl;
}
return 0;
}
/*
OUTPUT:
Enter total cabs: 4
Enter Car [Name & Coordinates(xi,yj)]:
Breeza 3 4
Swift 0 1
Safari 1 0
Nano 2 4
Car [Sorted Order]:
Safari 1 0 | Distance: 1
Swift 0 1 | Distance: 1
Nano 2 4 | Distance: 20
Breeza 3 4 | Distance: 25
*/