Reputation: 1
Given a grid of dimensions length X by height Y, how do I find the number of lines of length 3 that can be placed in the grid? Accounting for horizontal, vertical and diagonal lines.
EXAMPLE 3x3 grid - 3 horizontal lines, 3 vertical lines, 2 diagonal lines = 8 possible lines. 3x4 grid - 4 horizontal lines, 6 vertical lines, 4 diagonal lines = 14 possible lines.
Upvotes: 0
Views: 141
Reputation: 10545
Let's assume that X
and Y
are both at least 3.
In every row, there are X - 2
possible left-end points for a horizontal line of length three (all except the rightmost two columns). So the overall number of possible horizontal lines is Y * (X - 2)
.
By symmetry, the overall number of possible vertical lines is X * (Y - 2)
.
There are two types of diagonals according to their orientation. Consider those that are in upper-left to lower-right direction. Similar to the argument above, for the upper-left endpoint of any such diagonal of length three, there are X - 2
possible columns and Y - 2
possible rows. So the overall number of such diagonals is (X - 2) * (Y - 2)
.
By symmetry, the overall number of the other type of diagonal is the same.
So the overall number of lines of length three is Y * (X - 2) + X * (Y - 2) + 2 * (X - 2) * (Y - 2)
, which can be simplified to:
(2 * X - 3) * (2 * Y - 3) - 1
As expected, this formula does agree with your examples.
Upvotes: 1