I've been trying to implement Bresenham's line algorithm from the Wikipedia Page and I've encountered a strange issue that leads to an exception.
public static int[,] Line(int x0, int y0, int x1, int y1)
{
int arraySizeX = x1 - x0;
int arraySizeY = y1 - y0;
int [,] outputArray = new int[arraySizeX, arraySizeY];
//Bresenham's line algorithm from Wikipedia
double deltax = x1 - x0;
double deltay = y1 - y0;
double deltaerr = Math.Abs(deltay / deltax); // Assume deltax != 0 (line is not vertical),
double error;
error = 0.0;//no error at start
int y = 0;
for( int x = x0; x1 >= x; x++)
{
outputArray[x, y] = 1;
error += deltaerr;
while(error >= 0.5)
{
y = y + Math.Sign(deltay) * 1;
error = error - 1.0;
}
}
return outputArray;
}
And when I test it with:
Line(2, 1, 5, 3);
it return the exception:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
At this line:
error += deltaerr;
This happens on the second iteration of the for loop. At that point the two values are:
error -0.33333333333333337 double
and
deltaerr 0.66666666666666663 double
In my mind error should be assigned something like 0.3333. Any pointers as to what may have gone wrong?
This is my first question, so please tell me how I could improve in future. Thanks.
Solution: Pay close attention to all arrays in the code.
The error was actually on the line above where the code tried to reference an array position that didn't exist.