Skip to content

Instantly share code, notes, and snippets.

@s1moe2
Last active May 25, 2022 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s1moe2/a85a5da7e2af25397de326d9714a6bbc to your computer and use it in GitHub Desktop.
Save s1moe2/a85a5da7e2af25397de326d9714a6bbc to your computer and use it in GitHub Desktop.
Golang implementation of Bresenham's line algorithm
package main
import (
"fmt"
"math"
"os"
"strconv"
)
func main() {
x1, _ := strconv.Atoi(os.Args[1:][0])
y1, _ := strconv.Atoi(os.Args[1:][1])
p1 := point{
x: x1,
y: y1,
}
x2, _ := strconv.Atoi(os.Args[1:][2])
y2, _ := strconv.Atoi(os.Args[1:][3])
p2 := point{
x: x2,
y: y2,
}
fmt.Println(bresenhamPoints(p1, p2))
}
type point struct {
x int
y int
}
func bresenhamPoints(p1, p2 point) []point {
dx := int(math.Abs(float64(p2.x) - float64(p1.x)))
sx := -1
if p1.x < p2.x {
sx = 1
}
dy := -int(math.Abs(float64(p2.y) - float64(p1.y)))
sy := -1
if p1.y < p2.y {
sy = 1
}
err := dx + dy
points := []point{}
for {
points = append(points, point{p1.x, p1.y})
if p1.x == p2.x && p1.y == p2.y {
break
}
e2 := 2 * err
if e2 >= dy {
if p1.x == p2.x {
break
}
err = err + dy
p1.x = p1.x + sx
}
if e2 <= dx {
if p1.y == p2.y {
break
}
err = err + dx
p1.y = p1.y + sy
}
}
return points
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment