Created
June 24, 2020 20:42
-
-
Save EXayer/cfc5f06a1b689eeab29612254110c510 to your computer and use it in GitHub Desktop.
How many rectangles a matrix can fit?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Counts all rectangles inside matrix by loop. | |
* | |
* For 3x3: | |
* *_*_* // 1x1 = 4 | |
* *_*_* // 1x2 = 2 | |
* * * * // 2x1 = 2 | |
* // 2x2 = 1 | |
* | |
* @param int $n | |
* @param int $m | |
* @return int | |
*/ | |
function countRectInsideMatrix(int $n, int $m): int | |
{ | |
$w = $n; | |
$count = 0; | |
while (--$w > 0) { | |
$h = $m; | |
while (--$h > 0) { | |
for ($i = 1; $i <= $n - $w; $i++) { | |
for ($j = 1; $j <= $m - $h; $j++) { | |
if ($i + $w <= $n && $j + $h <= $m) { | |
$count++; | |
} | |
} | |
} | |
} | |
} | |
return $count; | |
} | |
$i = 1; | |
do { | |
printf("%dx%d = %d\n", $i, $i, countRectInsideMatrix($i, $i)); | |
printf("%dx%d = %d\n", $i + 1, $i, countRectInsideMatrix($i + 1, $i)); | |
printf("%dx%d = %d\n", $i, $i + 1, countRectInsideMatrix($i, $i + 1)); | |
} while ($i++ < 10); | |
// 1x1 = 0 | |
// 2x1 = 0 | |
// 1x2 = 0 | |
// 2x2 = 1 | |
// 3x2 = 3 | |
// 2x3 = 3 | |
// 3x3 = 9 | |
// 4x3 = 18 | |
// 3x4 = 18 | |
// 4x4 = 36 | |
// 5x4 = 60 | |
// 4x5 = 60 | |
// 5x5 = 100 | |
// 6x5 = 150 | |
// 5x6 = 150 | |
// 6x6 = 225 | |
// 7x6 = 315 | |
// 6x7 = 315 | |
// 7x7 = 441 | |
// 8x7 = 588 | |
// 7x8 = 588 | |
// 8x8 = 784 | |
// 9x8 = 1008 | |
// 8x9 = 1008 | |
// 9x9 = 1296 | |
// 10x9 = 1620 | |
// 9x10 = 1620 | |
// 10x10 = 2025 | |
// 11x10 = 2475 | |
// 10x11 = 2475 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment