Skip to content

Commit 71ad663

Browse files
committed
Add Generalized Bresenham Line Algorithm (all octants) for Hacktoberfest
1 parent 99a13d4 commit 71ad663

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Generalized Bresenham's Line Drawing Algorithm
3+
----------------------------------------------
4+
5+
Handles all possible line slopes and directions.
6+
7+
Reference:
8+
https://www.geeksforgeeks.org/dsa/bresenhams-line-generation-algorithm/
9+
10+
>>> generalized_bresenham_line((0, 0), (5, 3))
11+
[(0, 0), (1, 1), (2, 1), (3, 2), (4, 2), (5, 3)]
12+
>>> generalized_bresenham_line((5, 5), (2, 3))
13+
[(5, 5), (4, 4), (3, 4), (2, 3)]
14+
"""
15+
16+
import matplotlib.pyplot as plt
17+
18+
19+
def generalized_bresenham_line(
20+
p1: tuple[int, int], p2: tuple[int, int]
21+
) -> list[tuple[int, int]]:
22+
x1, y1 = p1
23+
x2, y2 = p2
24+
dx = abs(x2 - x1)
25+
dy = abs(y2 - y1)
26+
sx = 1 if x1 < x2 else -1
27+
sy = 1 if y1 < y2 else -1
28+
err = dx - dy
29+
30+
points = []
31+
32+
while True:
33+
points.append((x1, y1))
34+
if x1 == x2 and y1 == y2:
35+
break
36+
e2 = 2 * err
37+
if e2 > -dy:
38+
err -= dy
39+
x1 += sx
40+
if e2 < dx:
41+
err += dx
42+
y1 += sy
43+
44+
return points
45+
46+
47+
if __name__ == "__main__":
48+
import doctest
49+
50+
doctest.testmod()
51+
52+
x1 = int(input("Enter x1: "))
53+
y1 = int(input("Enter y1: "))
54+
x2 = int(input("Enter x2: "))
55+
y2 = int(input("Enter y2: "))
56+
57+
points = generalized_bresenham_line((x1, y1), (x2, y2))
58+
print("Generated points:", points)
59+
60+
xs, ys = zip(*points)
61+
plt.plot(xs, ys, marker="o")
62+
plt.title("Generalized Bresenham's Line Algorithm (All Slopes)")
63+
plt.grid()
64+
plt.show()

0 commit comments

Comments
 (0)