3
$\begingroup$

Given an NxN array, drawing a line from the edge's midpoint to the opposite field how can the N buckets be found covering the majority of the line's path?

A visual aid: enter image description here

Is there a better way to this than computing the linear equation and iteratively advancing in tiny steps to check which bucket we fall on? If not what is the lower limit step size to choose?

$\endgroup$
1
$\begingroup$

For the considered line you know the start position (xs, ys) and the end (xe, ye). For instance on the N=7 visual you provide, let's take the first upper left line:

xs = 0
ys = 4.5
xe = 7
ye = 2.5
(I use coordinates right, down starting from upper left corner).

Let's take a parameter t of the linear position on the line with t=0 on start and t=1 on end. You know how many verticals or horizontals your line crosses and at which t value. In our exemple:

  • 6 verticals crossed at t = v/7 with v=1 to 6 (not counting outlines).
  • 2 horizontal crossed at t = 0.25 and t = 0.75.

Now just sort t increasing all these crossings:

(1/7, V), (0.25, H) (2/7, V), (3/7, V), (4/7, V), (5/7, V), (0.75, H), (6/7, V).

They correspond to cell change starting in cell (1, 5) to cell (7, 3). So you can compute the relative length of the line in each cell. For instance:

cell (1, 5) L = 1/7-0 = 1/7
cell (2, 5) L = 0.25-1/7
...

And you know how to select the X pixels now.

$\endgroup$
  • $\begingroup$ Thanks. Let me take a closer look at it and I'll accept your answer once I got it translated into code $\endgroup$ – Kilian Jan 16 at 11:03
  • 1
    $\begingroup$ Ingenious but this seems much less efficient than Bresenham. $\endgroup$ – David Richerby Jan 16 at 11:26
  • $\begingroup$ It is more or less the same but it allows vectorial computation. Do not forget that when I say "sort", this can be done implicetly as both horizontal list and vertical list are already sorted. Bresenham is more interesting if you care on where exactly is the crossing point. $\endgroup$ – Vince Jan 16 at 13:26
1
$\begingroup$

You probably want to look at Bresenham's line drawing algorithm. Rather than moving along the line itself, you move along the $x$-coordinates a "pixel" (i.e., array entry) at a time and compute which $y$-value puts the greatest part of the line in the pixel $(x,y)$.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.