Hi their I have an excercise and below is my solution to it. Is their a better solution?
A figure stands in the 2-dimensional space on coordinate (Fx/Fy) and can move with one step in 8 directions to a neighboring field: (E SE S SW W NW N NE) The figure should move as fast as possible to a target point (Zx/Zy). First read the coordinates of the figure and the target point. Then move the figure along the shortest possible way to the destination, outputting the coordinates of each step and at the end outputting the number of steps required.
What I don't like on the code is how many lines of code I need.
#include <stdio.h>
int fx;
int fy;
int zx;
int zy;
int xgleich = 0;
int ygleich = 0;
int cnt = 1;
// Diagonale Funktion
int diagonalsteps(int fx,int zx)
{
while (xgleich == 0 && ygleich == 0)
{
if (fx < zx)
{
fx++;
}
else
{
fx--;
}
if (fy < zy)
{
fy++;
}
else
{
fy--;
}
printf("\n%dter Schritt: X:%d, Y=%d\n", cnt, fx,fy);
cnt++;
if (fx == zx)
{
xgleich = 1;
}
if (fy == zy)
{
ygleich = 1;
}
}
}
/* gerader Weg */
int geradesteps(int fy, int zy)
{
if (xgleich == 1)
{
if(fy < zy)
{
while (fy < zy)
{
fy++;
printf("\n%dter Schritt: X=%d, Y=%d\n", cnt, fx, fy);
cnt++;
}
}
if (ygleich == 1)
{
if (fx < zx)
{
while (fx < zx)
{
fx++;
printf("\n%dter Schritt: X=%d, Y=%d\n", cnt, fx, fy);
cnt++;
}
}
if (fx > zx)
{
while (fx > zx)
{
fx--;
printf("\n%dter Schritt: X=%d, Y=%d\n", cnt, fx, fy);
cnt++;
}
}
}
}
}
int main()
{
printf("Bitte geben Sie den Koordinaten Fx und Fy Punkt ein: ");
scanf("%d %d", &fx, &fy);
printf("%d und %d\n", fx, fy);
printf("Bitte geben Sie die Ziel Koordinaten Zx und Zy Punkt ein: ");
scanf("%d %d", &zx, &zy);
printf("%d und %d\n", zx, zy);
if (fx == zx)
{
xgleich = 1;
}
if (fy == zy)
{
ygleich = 1;
}
diagonalsteps(fx,zx);
geradesteps(fy,zy);
return 0;
}