-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosest_star.h
More file actions
62 lines (52 loc) · 1.44 KB
/
Copy pathclosest_star.h
File metadata and controls
62 lines (52 loc) · 1.44 KB
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
#ifndef CPP_ALGORITHM_CLOSEST_STAR_H
#define CPP_ALGORITHM_CLOSEST_STAR_H
#include <cmath>
#include <queue>
#include <vector>
namespace ClosestStar
{
struct Star
{
double x;
double y;
double z;
[[nodiscard]] double Distance() const { return std::sqrt((x * x) + (y * y) + (z * z)); }
[[nodiscard]] bool operator<(const Star& other) const { return Distance() < other.Distance(); }
};
/**
* \brief Find the closest star.
* \details Given a list of stars and their coordinates in a 3D space, find the closest star.
* \param stars a list of stars
* \param k number of closest stars to find
* \return the closest star
*/
std::priority_queue<Star> FindClosestStar(
std::vector<Star>& stars,
int k);
}
// ----------------------------------------------------------------------------
inline std::priority_queue<ClosestStar::Star> ClosestStar::FindClosestStar(
std::vector<Star>& stars,
const int k)
{
std::priority_queue<Star> max_heap;
while (!stars.empty())
{
Star star = stars.back();
stars.pop_back();
if (static_cast<int>(max_heap.size()) < k)
{
max_heap.push(star);
}
else
{
if (star.Distance() < max_heap.top().Distance())
{
max_heap.pop();
max_heap.push(star);
}
}
}
return max_heap;
}
#endif