356 Line Reflection
struct pair_hash {
inline std::size_t operator()(const std::pair<int, int> & v) const {
return hash<string>{}(to_string(v.first) + to_string(v.second));
}
};
unordered_set<pair<int, int>, pair_hash> add_to_set(const vector<pair<int, int>> &points) {
unordered_set<pair<int, int>, pair_hash> unique_points;
unique_points.reserve(points.size());
for (auto p : points)
unique_points.insert(p);
return unique_points;
}
pair<int, int> min_and_max_x_val(const vector<pair<int, int>>& points) {
int my_min = INT_MAX, my_max = INT_MIN;
for (auto &p : points) {
my_min = min(my_min, p.first);
my_max = max(my_max, p.first);
}
return {my_min, my_max};
}
bool isReflected(vector<pair<int, int>>& points) {
if (points.empty()) return true;
pair<int, int> min_max_x = min_and_max_x_val(points);
if (min_max_x.first == min_max_x.second) return true; // TODO: try without this later as well
double verify_this_y_axis = (abs(min_max_x.second - min_max_x.first) / 2.0) + min_max_x.first;
unordered_set<pair<int, int>, pair_hash> unique_points = add_to_set(points);
for (auto p : unique_points) {
double dist_to_axis = abs(verify_this_y_axis - p.first);
pair<int, int> reflected_analog;
if (p.first <= verify_this_y_axis)
reflected_analog = {p.first + (dist_to_axis) * 2, p.second};
else reflected_analog = { p.first - (dist_to_axis) * 2, p.second };
if (unique_points.find(reflected_analog) == unique_points.end())
return false;
}
return true;
}Last updated