Cross the yard without getting wet - c++

Here is the question:
There is a house with a backyard which is square bounded by
coordinates (0,0) in the southwest to (1000,1000) in
the northeast. In this yard there are a number of water sprinklers
placed to keep the lawn soaked in the middle of the summer. However,
it might or might not be possible to cross the yard without getting
soaked and without leaving the yard?
Input The input starts with a line containing an integer 1≤n≤1000, the
number of water sprinklers. A line follows for each sprinkler,
containing three integers: the (x,y)(x,y) location of the sprinkler
(0≤x,y,≤10000) and its range r (1≤r≤1000). The sprinklers will soak
anybody passing strictly within the range of the sprinkler (i.e.,
within distance strictly less than r).
The house is located on the west side (x=0) and a path is needed to
the east side of the yard (x=1000).
Output If you can find a path through the yard, output four real
numbers, separated by spaces, rounded to two digits after the decimal
place. These should be the coordinates at which you may enter and
leave the yard, respectively. If you can enter and leave at several
places, give the results with the highest y. If there is no way to get
through the yard without getting soaked, print a line containing
“IMPOSSIBLE”.
Sample Input
3
500 500 499
0 0 999
1000 1000 200
Sample output
0.00 1000.00 1000.00 800.00
Here is my thought process:
Define circle objects with x,y,r and write a function to determine if a given point is wet or not(inside the circle or not) on the circumference is not wet btw.
class circle {
int h;
int k;
int r;
public:
circle();
circle(int h, int k, int r){
this->h = h;
this->k = k;
this->r = r;
};
bool iswet(pair<int,int>* p){
if (pow(this->r - 0.001, 2) > (pow(p->first - this->h, 2) +
pow(p->second - this->k, 2) ) ) {
return true;
}
else
return false;
};
Then implement a depth first search, prioritizing to go up and right whenever possible.
However since circles are not guaranteed to be pass on integer coordinates an the result is expected in floats with double precision (xxx.xx). So if we keep everything in integers the grid suddenly becomes 100,000 x 100,000 which is way too big. Also the time limit is 1 sec.
So I thought ok lets stick to 1000x1000 and work with floats instead. Loop over int coordinates and whenever I hit a sprinkle just snap in the perimeter of the circle since we are safe in the perimeter. But in that case could not figure out how DFS work.
Here is the latest trial
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <deque>
#include <utility>
#include <unordered_set>
#include <iomanip>
using namespace std;
const int MAXY = 1e3;
const int MAXX = 1e3;
const int MINY = 0;
const int MINX = 0;
struct pair_hash {
inline std::size_t operator()(const std::pair<int,int> & v) const {
return v.first*31+v.second;
}
};
class circle {
int h;
int k;
int r;
public:
circle();
circle(int h, int k, int r){
this->h = h;
this->k = k;
this->r = r;
};
bool iswet(pair<float,float>* p){
if (pow(this->r - 0.001, 2) > (pow(p->first - this->h, 2) + pow(p->second - this->k, 2) ) ) {
this->closest_pair(p);
return true;
}
else
return false;
};
void closest_pair(pair<float,float>* p){
float vx = p->first - this->h;
float vy = p->second - this->k;
float magv = sqrt(vx * vx + vy * vy);
p->first = this->h + vx / magv * this->r;
p->second = this->k + vy / magv * this->r;
}
};
static bool test_sprinkles(vector<circle> &sprinkles, pair<float,float>* p){
for (int k = 0; k < sprinkles.size(); k++)
if (sprinkles[k].iswet(p)) return false;
return true;
}
int main(){
int n; // number of sprinkles
while (cin >> n){
vector<circle> sprinkles_array;
sprinkles_array.reserve(n);
int h, k, r;
while (n--){
cin >> h >> k >> r;
sprinkles_array.push_back(circle(h, k, r));
}/* code */
pair<float,float> enter = make_pair(0, MAXY);
deque<pair<float,float>> mystack;
mystack.push_back(enter);
pair<float,float>* cp;
bool found = false;
unordered_set<pair<float, float>, pair_hash> visited;
while (!mystack.empty()){
cp = &mystack.back();
if (cp->first == MAXX) {
found = true;
break;
}
visited.insert(*cp);
if (cp->second > MAXY || cp->second < MINY || cp ->first < MINX ) {
visited.insert(*cp);
mystack.pop_back();
continue;
}
if (!test_sprinkles(sprinkles_array,cp)) {
continue;
}
pair<int,int> newpair = make_pair(cp->first, cp->second + 1);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
newpair = make_pair(cp->first + 1 , cp->second);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
newpair = make_pair(cp->first, cp->second - 1);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
newpair = make_pair(cp->first - 1, cp->second);
if (visited.find(newpair) == visited.end()) {
mystack.push_back(newpair);
continue;
}
else visited.insert(newpair);
mystack.pop_back();
}
cout << setprecision(2);
cout << fixed;
if (found){
double xin = mystack.front().first;
double yin = mystack.front().second;
pair <float, float> p = mystack.back();
p.second++;
for (int k = 0; k < sprinkles_array.size(); k++)
if (sprinkles_array[k].iswet(&p)) break;
double xout = p.first;
double yout = p.second;
cout << xin << " " << yin << " " << xout << " " << yout << endl;
}
else
{
cout << "IMPOSSIBLE" << endl;
}
}
}

Yes #JosephIreland is right. Solved it with grouping intersecting (not touching) circles. Then these groups have maxy and min y coordinates. If it exceeds the yard miny and maxy the way is blocked.
Then these groups also have upper and lower intersection points with x=0 and x=1000 lines. If the upper points are larger than the yard maxy then the maximum entry/exit points are lower entery points.
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <utility>
#include <iomanip>
using namespace std;
const int MAXY = 1e3;
const int MAXX = 1e3;
const int MINY = 0;
const int MINX = 0;
struct circle {
int h;
int k;
int r;
float maxy;
float miny;
circle();
circle(int h, int k, int r){
this->h = h;
this->k = k;
this->r = r;
this->miny = this->k - r;
this->maxy = this->k + r;
};
};
struct group {
float maxy = -1;
float miny = -1;
vector<circle*> circles;
float upper_endy = -1;
float upper_starty = -1;
float lower_endy = -1;
float lower_starty = -1;
void add_circle(circle& c){
if ((c.maxy > this->maxy) || this->circles.empty() ) this->maxy = c.maxy;
if ((c.miny < this->miny) || this->circles.empty() ) this->miny = c.miny;
this->circles.push_back(&c);
// find where it crosses x=minx and x= maxx
float root = sqrt(pow(c.r, 2) - pow(MINX - c.h, 2));
float y1 = root + c.k;
float y2 = -root + c.k;
if (y1 > this->upper_starty) this->upper_starty = y1;
if (y2 > this->lower_starty) this->lower_starty = y2;
root = sqrt(pow(c.r, 2) - pow(MAXX - c.h, 2));
y1 = root + c.k;
y2 = -root + c.k;
if (y1 > this->upper_endy) this->upper_endy = y1;
if (y2 > this->lower_endy) this->lower_endy = y2;
};
bool does_intersect(circle& c1){
for(circle* c2 : circles){
float dist = sqrt(pow(c1.h - c2->h,2)) + sqrt(pow(c1.k - c2->k,2));
(dist < (c1.r + c2->r)) ? true : false;
};
};
};
int main(){
int n; // number of sprinkles
while (cin >> n){
vector<circle> sprinkles_array;
sprinkles_array.reserve(n);
int h, k, r;
while (n--){
cin >> h >> k >> r;
sprinkles_array.push_back(circle(h, k, r));
}/* code */
vector<group> groups;
group newgroup;
newgroup.add_circle(sprinkles_array[0]);
groups.push_back(newgroup);
for (int i = 1; i < sprinkles_array.size(); i++){
bool no_group = true;
for (group g:groups){
if (g.does_intersect(sprinkles_array[i])){
g.add_circle(sprinkles_array[i]);
no_group = false;
break;
}
}
if (no_group) {
group newgroup;
newgroup.add_circle(sprinkles_array[i]);
groups.push_back(newgroup);
}
}
float entery = MAXY;
float exity = MAXY;
bool found = true;
for (group g : groups){
if ((g.miny < MINY) && (g.maxy > MAXY)){
found = false;
break;
}
if (g.upper_starty > entery)
entery = g.lower_starty;
if (g.upper_endy > exity)
exity = g.lower_endy;
}
cout << setprecision(2);
cout << fixed;
if (found){
cout << float(MINX) << " " << entery << " " << float(MAXX) << " " << exity << endl;
}
else
{
cout << "IMPOSSIBLE" << endl;
}
}
}

Related

expression preceeding of apparent call must have pointer-to func type

I have a class that I'm trying to use, but in main function ёstartё doesn't execute with following error expression preceeding of apparent call must have pointer-to func type
#include <queue>
#include <limits>
#include <cmath>
#include <iostream>
// represents a single pixel
class Node {
public:
int idx; // index in the flattened grid
float cost; // cost of traversing this pixel
Node(int i, float c) : idx(i), cost(c) {}
};
bool operator<(const Node &n1, const Node &n2) {
return n1.cost > n2.cost;
}
bool operator==(const Node &n1, const Node &n2) {
return n1.idx == n2.idx;
}
// various grid heuristics:
// http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S7
float linf_norm(int i0, int j0, int i1, int j1) {
return std::max(std::abs(i0 - i1), std::abs(j0 - j1));
}
// manhattan distance
float l1_norm(int i0, int j0, int i1, int j1) {
return std::abs(i0 - i1) + std::abs(j0 - j1);
}
// weights: flattened h x w grid of costs
// h, w: height and width of grid
// start, goal: index of start/goal in flattened grid
// diag_ok: if true, allows diagonal moves (8-conn.)
// paths (output): for each node, stores previous node in path
class Astar {
public:
float* weights = nullptr;
int h;
int w;
int start;
int goal;
bool diag_ok;
int* paths = nullptr;
void setVariables(float* weightsInput, int hInput, int wInput, int startInput, int goalInput, bool diag_okInput, int* pathsInput) {
weights = weightsInput;
h = hInput;
w = wInput;
start = startInput;
goal = goalInput;
diag_ok = diag_okInput;
paths = pathsInput;
}
void start() {
const float INF = std::numeric_limits<float>::infinity();
std::cout << "width : " << w << " " << "height : " << h << std::endl;
std::cout << "start : " << start << " goal : " << goal << std::endl;
Node start_node(start, 0.);
Node goal_node(goal, 0.);
float* costs = new float[h * w];
for (int i = 0; i < h * w; ++i)
costs[i] = INF;
costs[start] = 0.;
std::priority_queue<Node> nodes_to_visit;
nodes_to_visit.push(start_node);
int* nbrs = new int[3];
bool solution_found = false;
while (!nodes_to_visit.empty()) {
// .top() doesn't actually remove the node
Node cur = nodes_to_visit.top();
if (cur == goal_node) {
solution_found = true;
break;
}
nodes_to_visit.pop();
int row = cur.idx / w;
int col = cur.idx % w;
bool allowDiag;
// check bounds and find up to eight neighbors: top to bottom, left to right
// can move only right\down\down - right so we can max have 3 neighbours
nbrs[0] = (col + 1 < w) ? cur.idx + 1 : -1; // right
nbrs[1] = (row + 1 < h) ? cur.idx + w : -1; // down
allowDiag = (weights[cur.idx + w + 1] == 14) ? true : false;
nbrs[2] = (allowDiag) ? cur.idx + w + 1 : -1; // down-right
std::cout << "right-bottom node : " << weights[cur.idx + w + 1] << std::endl;
float heuristic_cost;
for (int i = 0; i < 3; ++i) {
std::cout << "neighbours : " << nbrs[i] << " ";
if (nbrs[i] >= 0) {
// the sum of the cost so far and the cost of this move
float new_cost = costs[cur.idx] + weights[nbrs[i]];
if (new_cost < costs[nbrs[i]]) {
// estimate the cost to the goal based on legal moves
if (allowDiag) {
heuristic_cost = linf_norm(nbrs[i] / w, nbrs[i] % w,
goal / w, goal % w);
}
else {
heuristic_cost = l1_norm(nbrs[i] / w, nbrs[i] % w,
goal / w, goal % w);
}
// paths with lower expected cost are explored first
float priority = new_cost + heuristic_cost;
nodes_to_visit.push(Node(nbrs[i], priority));
costs[nbrs[i]] = new_cost;
paths[nbrs[i]] = cur.idx;
}
}
}
std::cout << "\n";
}
delete[] costs;
delete[] nbrs;
//return solution_found;
}
};
int main() {
Astar astarPathfinding;
float* weights;
int h;
int w;
int start;
int goal;
bool diag_ok;
int* paths;
astarPathfinding.setVariables(weights, h, w, start, goal, diag_ok, paths);
astarPathfinding.start(); // error
return 0;
}
You have "start" as member and "start" as function.
Rename one of them will fix your error.

'std::out_of_range' error from code

The following error message was received after running my code located at the end of the message:
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
I'm sorry for the length of the code. It appears that the error is coming from when I am calling the numerov function within the f function. If you are able to determine what the error is would you please let me know? Thank you!
#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
using namespace std;
int nx = 500, m = 10, ni = 10;
double x1 = 0, x2 = 1, h = (x2 - x1)/nx;
int nr, nl;
vector<double> ul, q, u;
//Method to achieve the evenly spaced Simpson rule
double simpson(vector <double> y, double h)
{
int n = y.size() - 1;
double s0 = 0, s1 = 0, s2 = 0;
for (int i = 1; i < n; i += 2)
{
s0 += y.at(i);
s1 += y.at(i-1);
s2 += y.at(i+1);
}
double s = (s1 + 4*s0 + s2)/3;
//Add the last slice separately for an even n+1
if ((n+1)%2 == 0)
return h*(s + (5*y.at(n) + 8*y.at(n-1) - y.at(n-2))/12);
else
return h*2;
}
//Method to perform the Numerov integration
vector <double> numerov(int m, double h, double u0, double u1, double q)
{
vector<double> u;
u.push_back(u0);
u.push_back(u1);
double g = h*h/12;
for (int i = 1; i < m+1; i++)
{
double c0 = 1 + g*q;
double c1 = 2 - 10*g*q;
double c2 = 1 + g*q;
double d = g*(0);
u.push_back((c1*u.at(i) - c0*u.at(i-1) + d)/c2);
}
return u;
}
//Method to provide the function for the root search
double f(double x)
{
vector<double> w;
vector<double> j = numerov(nx + 1, h, 0.0, 0.001, x);
for (int i = 0; i < 0; i++)
{
w.push_back(j.at(i));
}
return w.at(0);
}
//Method to carry out the secant search
double secant(int n, double del, double x, double dx)
{
int k = 0;
double x1 = x + dx;
while ((abs(dx) > del) && (k < n))
{
double d = f(x1) - f(x);
double x2 = x1 - f(x1)*(x1 - x)/d;
x = x1;
x1 = x2;
dx = x1 - x;
k++;
}
if (k == n)
cout << "Convergence not found after " << n << " iterations." << endl;
return x1;
}
int main()
{
double del = 1e-6, e = 0, de = 0.1;
//Find the eigenvalue via the secant method
e = secant (ni, del, e, de);
//Find the solution u(x)
u = numerov(nx + 1, h, 0.0, 0.01, e);
//Output the wavefunction to a file
ofstream myfile ("Problem 2.txt");
if (myfile.is_open())
{
myfile << "Input" << "\t" << "u(x)" << endl;
double x = x1;
double mh = m*h;
for (int i = 0; i <= nx; i += m)
{
myfile << x << "\t" << u.at(i) << endl;
x += mh;
}
myfile.close();
}
return 0;
}
vector<double> w;
for (int i = 0; i < 0; i++)
{
w.push_back(j.at(i));
}
return w.at(0);
w will have nothing in it, since that loop will run 0 times. Thus, w.at(0) will throw the out of range error.
Why do you think the problem is in the numerov function?
I see an error in the function f?
vector<double> w;
vector<double> j = numerov(nx + 1, h, 0.0, 0.001, x);
for (int i = 0; i < 0; i++)
{
w.push_back(j.at(i));
}
return w.at(0);
There is nothing on vector w and you try to access element 0.

2D Poisson-disk sampling in a specific square (not a unit square) with specific minimum distance

Is there any way I can modify the poisson-disk points generator finding here.I need to generate new poisson points using the coordinates of points in the textfile.txt to improve the distribution. below the c++ code of poisson-disk sampling in a unit square.
poissonGenerator.h:
#include <vector>
#include <random>
#include <stdint.h>
#include <time.h>
namespace PoissoGenerator
{
class DefaultPRNG
{
public:
DefaultPRNG()
: m_Gen(std::random_device()())
, m_Dis(0.0f, 1.f)
{
// prepare PRNG
m_Gen.seed(time(nullptr));
}
explicit DefaultPRNG(unsigned short seed)
: m_Gen(seed)
, m_Dis(0.0f, 1.f)
{
}
double RandomDouble()
{
return static_cast <double>(m_Dis(m_Gen));
}
int RandomInt(int Max)
{
std::uniform_int_distribution<> DisInt(0, Max);
return DisInt(m_Gen);
}
private:
std::mt19937 m_Gen;
std::uniform_real_distribution<double> m_Dis;
};
struct sPoint
{
sPoint()
: x(0)
, y(0)
, m_valid(false){}
sPoint(double X, double Y)
: x(X)
, y(Y)
, m_valid(true){}
double x;
double y;
bool m_valid;
//
bool IsInRectangle() const
{
return x >= 0 && y >= 0 && x <= 1 && y <= 1;
}
//
bool IsInCircle() const
{
double fx = x - 0.5f;
double fy = y - 0.5f;
return (fx*fx + fy*fy) <= 0.25f;
}
};
struct sGridPoint
{
sGridPoint(int X, int Y)
: x(X)
, y(Y)
{}
int x;
int y;
};
double GetDistance(const sPoint& P1, const sPoint& P2)
{
return sqrt((P1.x - P2.x)*(P1.x - P2.x) + (P1.y - P2.y)*(P1.y - P2.y));
}
sGridPoint ImageToGrid(const sPoint& P, double CellSize)
{
return sGridPoint((int)(P.x / CellSize), (int)(P.y / CellSize));
}
struct sGrid
{
sGrid(int W, int H, double CellSize)
: m_W(W)
, m_H(H)
, m_CellSize(CellSize)
{
m_Grid.resize((m_H));
for (auto i = m_Grid.begin(); i != m_Grid.end(); i++){ i->resize(m_W); }
}
void Insert(const sPoint& P)
{
sGridPoint G = ImageToGrid(P, m_CellSize);
m_Grid[G.x][G.y] = P;
}
bool IsInNeighbourhood(sPoint Point, double MinDist, double CellSize)
{
sGridPoint G = ImageToGrid(Point, CellSize);
//number of adjacent cell to look for neighbour points
const int D = 5;
// Scan the neighbourhood of the Point in the grid
for (int i = G.x - D; i < G.x + D; i++)
{
for (int j = G.y - D; j < G.y + D; j++)
{
if (i >= 0 && i < m_W && j >= 0 && j < m_H)
{
sPoint P = m_Grid[i][j];
if (P.m_valid && GetDistance(P, Point) < MinDist){ return true; }
}
}
}
return false;
}
private:
int m_H;
int m_W;
double m_CellSize;
std::vector< std::vector< sPoint> > m_Grid;
};
template <typename PRNG>
sPoint PopRandom(std::vector<sPoint>& Points, PRNG& Generator)
{
const int Idx = Generator.RandomInt(Points.size() - 1);
const sPoint P = Points[Idx];
Points.erase(Points.begin() + Idx);
return P;
}
template <typename PRNG>
sPoint GenerateRandomPointAround(const sPoint& P, double MinDist, PRNG& Generator)
{
// Start with non-uniform distribution
double R1 = Generator.RandomDouble();
double R2 = Generator.RandomDouble();
// radius should be between MinDist and 2 * MinDist
double Radius = MinDist * (R1 + 1.0f);
//random angle
double Angle = 2 * 3.141592653589f * R2;
// the new point is generated around the point (x, y)
double X = P.x + Radius * cos(Angle);
double Y = P.y + Radius * sin(Angle);
return sPoint(X, Y);
}
// Return a vector of generated points
// NewPointsCount - refer to bridson-siggraph07-poissondisk.pdf
// for details (the value 'k')
// Circle - 'true' to fill a circle, 'false' to fill a rectangle
// MinDist - minimal distance estimator, use negative value for default
template <typename PRNG = DefaultPRNG>
std::vector<sPoint> GeneratePoissonPoints(rsize_t NumPoints, PRNG& Generator, int NewPointsCount = 30,
bool Circle = true, double MinDist = -1.0f)
{
if (MinDist < 0.0f)
{
MinDist = sqrt(double(NumPoints)) / double(NumPoints);
}
std::vector <sPoint> SamplePoints;
std::vector <sPoint> ProcessList;
// create the grid
double CellSize = MinDist / sqrt(2.0f);
int GridW = (int)(ceil)(1.0f / CellSize);
int GridH = (int)(ceil)(1.0f / CellSize);
sGrid Grid(GridW, GridH, CellSize);
sPoint FirstPoint;
do
{
FirstPoint = sPoint(Generator.RandomDouble(), Generator.RandomDouble());
} while (!(Circle ? FirstPoint.IsInCircle() : FirstPoint.IsInRectangle()));
//Update containers
ProcessList.push_back(FirstPoint);
SamplePoints.push_back(FirstPoint);
Grid.Insert(FirstPoint);
// generate new points for each point in the queue
while (!ProcessList.empty() && SamplePoints.size() < NumPoints)
{
#if POISSON_PROGRESS_INDICATOR
// a progress indicator, kind of
if (SamplePoints.size() % 100 == 0) std::cout << ".";
#endif // POISSON_PROGRESS_INDICATOR
sPoint Point = PopRandom<PRNG>(ProcessList, Generator);
for (int i = 0; i < NewPointsCount; i++)
{
sPoint NewPoint = GenerateRandomPointAround(Point, MinDist, Generator);
bool Fits = Circle ? NewPoint.IsInCircle() : NewPoint.IsInRectangle();
if (Fits && !Grid.IsInNeighbourhood(NewPoint, MinDist, CellSize))
{
ProcessList.push_back(NewPoint);
SamplePoints.push_back(NewPoint);
Grid.Insert(NewPoint);
continue;
}
}
}
#if POISSON_PROGRESS_INDICATOR
std::cout << std::endl << std::endl;
#endif // POISSON_PROGRESS_INDICATOR
return SamplePoints;
}
}
and the main program is:
poisson.cpp
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <fstream>
#include <memory.h>
#define POISSON_PROGRESS_INDICATOR 1
#include "PoissonGenerator.h"
const int NumPoints = 20000; // minimal number of points to generate
int main()
{
PoissonGenerator::DefaultPRNG PRNG;
const auto Points =
PoissonGenerator::GeneratePoissonPoints(NumPoints,PRNG);
std::ofstream File("Poisson.txt", std::ios::out);
File << "NumPoints = " << Points.size() << std::endl;
for (const auto& p : Points)
{
File << " " << p.x << " " << p.y << std::endl;
}
system("PAUSE");
return 0;
}
Suppose you have a point in the space [0,1] x [0,1], in the form of a std::pair<double, double>, but desire points in the space [x,y] x [w,z].
The function object
struct ProjectTo {
double x, y, w, z;
std::pair<double, double> operator(std::pair<double, double> in)
{
return std::make_pair(in.first * (y - x) + x, in.second * (z - w) + w);
}
};
will transform such an input point into the desired output point.
Suppose further you have a std::vector<std::pair<double, double>> points, all drawn from the input distribution.
std::copy(points.begin(), points.end(), points.begin(), ProjectTo{ x, y, w, z });
Now you have a vector of points in the output space.

Calculation of distance of points with double coordinates

While I was writing a c++ program I stuck on a problem. In brief, my program input is one integer which is the number of coordinates that I have to input. And I have an algorithm that calculates the passed distance between all of the points. Here is my algorithm:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
const double PI = 3.14;
const double rightXLimit = 5;
const double leftXLimit = -5;
const double topYLimit = 2;
const double bottomYLimit = -2;
const int ARR_SIZE = 100;
bool IsPointInRules(double x, double y)
{
if ((x >= leftXLimit && x <= rightXLimit) && (y >= bottomYLimit && y <= topYLimit))
{
return true;
}
return false;
}
double checkLimitsAndDistCalc(double x, double y, double x1, double y1)
{
if (!(IsPointInRules(x, y) || IsPointInRules(x1, y1)))
{
return 0;
}
else if (IsPointInRules(x, y) && (!IsPointInRules(x1, y1)))
{
if (x1 <= leftXLimit)
{
x1 = leftXLimit;
}
if (x1 >= rightXLimit)
{
x1 = rightXLimit;
}
if (y1 <= bottomYLimit)
{
y1 = bottomYLimit;
}
if (y1 >= topYLimit)
{
y1 = topYLimit;
}
}
else if ((!IsPointInRules(x, y)) && IsPointInRules(x1, y1))
{
if (x <= leftXLimit)
{
x = leftXLimit;
}
if (x >= rightXLimit)
{
x = rightXLimit;
}
if (y <= bottomYLimit)
{
y = bottomYLimit;
}
if (y >= topYLimit)
{
y = topYLimit;
}
}
double distance = sqrt(pow(x1 - x, 2) + pow(y1 - y, 2));
double result = ((PI * distance / 2) + distance) / 2;
//cout << setw(3) << x << setw(3) << y << setw(3) << x1 << setw(3) << y1 << " --> " << distance << " --> " << result << endl;
return result;
}
double calculateDistance(double* arrOne, double* arrTwo, int n)
{
double finalResult = 0;
for (int i = 0; i < n - 1; i++)
{
double getDistance = checkLimitsAndDistCalc(arrOne[i], arrTwo[i], arrOne[i + 1], arrTwo[i + 1]);
finalResult += getDistance;
}
return finalResult;
}
int main()
{
double coordsArrX[ARR_SIZE];
double coordsArrY[ARR_SIZE];
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> coordsArrX[i];
cin >> coordsArrY[i];
}
cout << setprecision(3) << fixed << calculateDistance(coordsArrX, coordsArrY, n) << '\n';
}
The problem is when I enter integers like coordinates the distance is wrong, but when enter double the distance is right and I can not find where is the problem. Here I tried some auto tests:
The problem is when I enter integers like coordinates the distance is wrong, but when enter double the distance is right and I can not find where is the problem.
That is an incorrect conclusion. The output is same whether you enter the coordinates using what appears to be integers or floating point numbers.
The output obtained using
7
0 0
0 3
-2 4
-1 1
-3 -1
4 1
6 3
is the same as using
7
0.0 0.0
0.0 3.0
-2.0 4.0
-1.0 1.0
-3.0 -1.0
4.0 1.0
6.0 3.0
See the output from using floating point input at http://ideone.com/fxgbga.
It appears that there is something else in your program that is not working as you are expecting.

Initializing dynamic pointer to multidimensional array

I am new to programming and am trying to implement A star search algorithm on C++. I am having segmentation fault:11 because of not initializing my pointer. I have tried it several different ways to no avail.
I am still confused about the whole pointer and dynamic memory allocation concept.
Can anyone help me figure it out? Thank you.
#include <iostream>
#include <vector>
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
// Definition of the heuristic. The heuristic in this problem is the distance between
// two coordinates
double heuristic(double x1, double y1, double x2, double y2) {
double dx, dy;
dx = x1 - x2;
dy = y1 - y2;
return sqrt(dx*dx - dy*dy);
//return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
}
// ----- A Star Search Algorithm (f = g + h)----
double** a_star_search(double points[][2]) {
int count = 1;
double** points1 = NULL;
// points1[10][2];
double x1 = points[0][0];
double y1 = points[0][1];
points1[count - 1][0] = x1;
points1[count - 1][1] = y1;
while (count <= 10) {
double tempx1;
double tempy1;
double distance = 10000000;
for (int i = 0; i < 10; i++) {
if (points[i][0] != 0 && points[i][1] != 0) {
double distance2 = heuristic(x1, y1, points[i][0], points[i][1]);
if (distance2 < distance) {
tempx1 = points[i][0];
tempy1 = points[i][1];
distance = distance2;
}
}
}
x1 = tempx1;
y1 = tempy1;
count++;
points1[count - 1][0] = x1;
points1[count - 1][1] = y1;
}
return points1;
}
int main() {
double points[7][2];
int counter = 0;
ifstream infile("waypoints.txt");
int a, b;
while (infile >> a >> b)
{
points[counter][0] = a;
points[counter][1] = b;
counter++;
}
points[6][0] = points[0][0];
points[6][1] = points[0][1];
double** points1 = a_star_search(points);
cout << "Initial Sequence: ";
for (int i = 0;i < 7;i++) {
cout << "(" <<points[i][0] << " , " << points[i][1] << "), ";
}
cout << "\n\nOptimized Sequence: ";
for (int i = 0;i < 7;i++) {
cout << "(" << points1[i][0] << " , " << points1[i][1] << "), ";
}
cout << "\n\nTotal Distance after A* search: ";
double totaldistance = 0;
for (int i = 0;i < 6;i++) {
double dis = heuristic(points1[i][0], points1[i][1], points1[i + 1][0], points1[i + 1][1]);
cout << dis << "+";
totaldistance = totaldistance + dis;
}
cout<< "=" << totaldistance <<endl;
}
You are not allocating memory dynamically for double** points1 variable after setting it to NULL in your a_star_search function. As pointed out by #user4581301, use std::vector. This will simplify your code significantly and worth spending the time to learn STL containers.