Skip to content

Instantly share code, notes, and snippets.

@linuxlizard
Created June 6, 2023 13:50
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 linuxlizard/e7cc69ee71ca12e87896ec1abc2813f7 to your computer and use it in GitHub Desktop.
Save linuxlizard/e7cc69ee71ca12e87896ec1abc2813f7 to your computer and use it in GitHub Desktop.
Bresenham's line algorithm in Rust via Google Bard
// via bard.google.com
use std::iter::Iterator;
struct Bresenham {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Bresenham {
fn new(x1: i32, y1: i32, x2: i32, y2: i32) -> Self {
Self { x1, y1, x2, y2 }
}
fn draw(&self) -> impl Iterator<Item = (i32, i32)> {
let dx = self.x2 - self.x1;
let dy = self.y2 - self.y1;
let step = if dy > 0 { 1 } else { -1 };
let mut y = self.y1;
(self.x1..self.x2 + 1)
.map(|x| (x, y))
.chain(std::iter::repeat((self.x2, y)))
.map(|(x, y)| {
let mut err = (dy * x) - (dx * y);
while err > 0 {
y += step;
err -= 2 * dy;
}
(x, y)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment