Quantcast
Channel: Active questions tagged row - Stack Overflow
Viewing all articles
Browse latest Browse all 452

Bresenham distance for shifted rows

$
0
0

I am currently trying to visualise and calculate the Bresenham distance (with the corresponding algorithm) between two points of a grid where every second row is shifted like this:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0

I have tried this in python and java (I would need the code in java but python code is also nice as it is way faster to write). None of my solutions I came up with contain the correct solution. In both examples I am trying to get to point 0 | 0 to point 8 | 4.

def draw_line(grid, x0, y0, x1, y1):    dx = abs(x1 - x0)    dy = abs(y1 - y0)    sx = 1 if x0 < x1 else -1    sy = 1 if y0 < y1 else -1    err = dx - dy    while x0 != x1 or y0 != y1:        grid[y0][x0] = 1  # Mark the cell as part of the line        e2 = 2 * err        if e2 > -dy:            err -= dy            x0 += sx        if e2 < dx:            err += dx            y0 += sy    # Mark the last cell as part of the line    grid[y1][x1] = 1# Example usage:grid = [[0] * 9 for _ in range(5)]  # Initialize a 5x9 grid with zeros# Draw a line from (1, 1) to (7, 3)draw_line(grid, 0, 0, 8, 4)# Print the gridfor row, i in zip(grid, range(len(grid))):    if i % 2 == 1:        print('', end='')    print(''.join(map(str, row)))

This outputs:

1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 00 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 00 0 0 0 0 0 0 0 1

My example in java looks like this:

public static List<Point> getVisitedCoordinates(Point startPoint, Point endPoint) {        List<Point> visitedCoordinates = new ArrayList<>();        int x1 = startPoint.getX();        int y1 = startPoint.getY();        int x2 = endPoint.getX();        int y2 = endPoint.getY();        int dx = Math.abs(x2 - x1);        int dy = Math.abs(y2 - y1);        int sx = x1 < x2 ? 1 : -1;        int sy = y1 < y2 ? 1 : -1;        int err = dx - dy;        while (x1 != x2 || y1 != y2) {            visitedCoordinates.add(new Point(x1, y1));            int e2 = 2 * err;            if (e2 > -dy) {                err -= dy;                x1 += sx;            }            if (e2 < dx) {                err += dx;                y1 += sy;            }        }        visitedCoordinates.add(new Point(x1, y1));        return visitedCoordinates;    }

which outputs

1 1 0 0 0 0 0 0 0  0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0  0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1

The correct solution I want is

1 1 0 0 0 0 0 0 0  0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0  0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1

In conclusion every marked field has to be physically next to another one (every 1 is required to have another 1 in a nearby field)


Viewing all articles
Browse latest Browse all 452

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>