Gatoninja Gatoninja - 1 year ago 95
C++ Question

The accuracy of my algorithm is perfect with small numbers and drop when numbers are larger, but not always

There is a game in which i have to program the AI and compete with other programers. I am playing that game. It consists in a race, your pod have to pass through some checkpoints in order.

You have some input arguments to use in your algorithm:

nextCheckpoint (x,y) -> nX,nY
lastCheckpoint (x,y) -> lnX,lnY
currentposition (x,y) -> x,y

and the output of the code is the directión and the thrust.

int pod::errorX(){
int R[2];
int X1;
float b;
int DeltaX;
//Vector of the line between Checkpoints
R[0] = nX-lnX;
R[1] = nY-lnY;
//calculation of the distance in the X axis between the ship and the line
b =(R[0]*(lnX-x) + R[1]*(lnY-y))/((-pow(R[0],2))-(pow(R[1],2)));
X1 = lnY + b*R[0];
DeltaX = x-X1;
cerr<<"Dx: "<<DeltaX<<endl;
return DeltaX;


I also have the equivalent pod::errorY()


DirectionX = nX-errorX();
DirectionY = nY-errorY();

Here some pictures of what I am doing:

the theory of what should happen

I want to do this becouse most of the times the inertia make my ship orbitate the checkpoints, this consume a lot of time and makes me loose the race.

Well now let's face the problem, it works sometimes and others is not even close.

When the inputs are small.

nX= 2;
nY= 2;

The output is:

directionX = 3
directionY = 1

But when they are bigger:

nX= 6553;
nY= 7817;

the output:


I do not know what happen. Maybe becouse b is decimal? is there any error that i havent seen?

Maybe this code is more confortable to test becouse you dont need the game:

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main()

int lnX = 13044;
int lnY = 7817;
int nX = 13044;
int nY = 1908;

int x = 13921;
int y = 3530;

int R[2]={};

//Vector de la recta entre Checkpoints
R[0] = nX-lnX;
R[1] = nY-lnY;
//puro algebra, para calcular el desfase de X
int X1,DeltaX;
long double b;
b =(R[0]*(lnX-x) + R[1]*(lnY-y))/((-pow(R[0],2))-(pow(R[1],2)));
X1 = lnY + b*R[0];
DeltaX = x-X1;
//desfase de y;
int Y1,DeltaY;
Y1 = lnY+b*R[1];
DeltaY = y-Y1;

int DirectionX;
int DirectionY;

DirectionX = nX-DeltaX;
DirectionY = nY-DeltaY;
cout<<X1<<" "<<Y1<<endl;
cout<<DeltaX<<" "<<DeltaY<<endl;
cout<<b<<" "<<DirectionX<< " "<<DirectionY<<endl;

Answer Source

Is this line right?: X1 = lnY + b*R[0]; Or should it be X1 = lnX + b*R[0];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download