/* Points.cpp - Implementing a data structure that holds a collection of n-dimensional points, and implements a function that is the closest distance to any of the points. James S. Plank CS494/594 Lecture notes. Fri May 15 15:28:39 EDT 2020 */ #include "points.hpp" #include #include #include using namespace std; typedef std::runtime_error SRE; void Points::Read(istream &in) { double d; istringstream ss; vector empty; size_t point_index; string line; try { p.clear(); /* Read each line into p. Lines can't be empty and they have to have the same number of points. */ while(getline(in, line)) { ss.clear(); ss.str(line); point_index = p.size(); p.push_back(empty); while (ss >> d) { if (d < 0 || d > 10) throw SRE("Points::Read() -- point not between 0 and 10"); p[point_index].push_back(d); } if (p[point_index].size() == 0) throw SRE("Points::Read() -- empty lines are disallowed"); if (p[point_index].size() != p[0].size()) { throw SRE("Points::Read() -- all lines need the same number of values"); } } if (p.size() == 0) throw SRE("Points::Read() - Empty input"); /* If we've caught an error, clear p and re-throw the exception. */ } catch (const SRE &e) { p.clear(); throw e; } } /* This function returns the minimum distance to a point in p. */ double Points::Min_Distance(const vector &x) const { double min_distance, d, tmp; size_t i, j; /* Error check */ if (p.size() == 0) throw SRE("Points::Min_Distance() - No points defined in the data structure"); if (x.size() != p[0].size()) throw SRE("Points::Min_Distance(): x is the wrong size"); min_distance = 0; for (i = 0; i < p.size(); i++) { d = 0; for (j = 0; j < p[i].size(); j++) { tmp = x[j] - p[i][j]; d += (tmp * tmp); } d = sqrt(d); if (i == 0 || d < min_distance) min_distance = d; } return min_distance; }